ANSI C -数组上的更高元素

0g0grzrc  于 2023-03-22  发布在  其他
关注(0)|答案(2)|浏览(122)

我有一些问题,我的代码,以获得最大的数字对一个数组的5个元素,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

float timerunner1[4];
int x;

int main() {

for(x=1;x<6;x++) {
    printf("Give me the time of runner 1: ");
    scanf("%f",timerunner1[x]);
}
return 0;
}

这工作得很好,输出是:

Give me the time of runner 1:  14
Give me the time of runner 1:  3
Give me the time of runner 1:  10
Give me the time of runner 1:  5
Give me the time of runner 1:  2

我怎样才能得到数组的最高和最低的数字?也许使用for或if..如何?
谢谢!

omqzjyyz

omqzjyyz1#

它实际上不起作用,你需要使用运算符'&'的地址来存储数组中的值。
扫描文件(“%f”,&timerunner1[x]);
此外,数组的大小不足以存储循环所需的6个整数,并且数组的下标从0开始到5结束(对于6个元素)。
然后,您可以在阅读所有值后再执行一次循环来计算最大值,或者按如下所示进行计算:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

float timerunner1[6];
int x;
float maximum = 0.0f;

int main() {

for (x = 0; x < 6; x++) {
    printf("Give me the time of runner 1: ");
    scanf("%f", &timerunner1[x]);
    maximum = maximum > timerunner1[x] ? maximum : timerunner1[x];
}

printf("%f\n", maximum);

return 0;
}

此外,这段代码只适用于正值,因为最大值被初始化为零,并且总是大于任何负值,如果你需要负值,你应该能够实验并弄清楚。

nzkunb0c

nzkunb0c2#

好吧,在这个程序中,你将不得不手动加载每个球员的时间。

/* StackFlow

Find the highest of an array of 5 numbers */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {

    float timerunner1[ 5 ] ={ 0 };
    float highest;
    int highestindex, i;

    /* Data input*/
    for( i = 0; i < 5; i++ ){
            printf( "\nEnter the %d element of the array: ", i );
            scanf( %f, timerunner1[ i ] );
    }

    /* Considering that the first generated number is the highest*/
    highest = timerunner1[ 0 ];
    highestindex = 0;

    /* The first element of an array is [0] not [1]*/
    for( i = 1; i < 5; i++ ) {

        /* if the next element in the array is higher than the previous*/
        if ( highest < timerunner1[ i ]){
            highest = timerunner1[ i ];
            highestindex = i;
        }

    }

    printf("\nThe highest time of the runner %d is: %f \n", highestindex, highest);
    return 1;
}

相关问题