-3

我的代码有一些问题,以获得 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 .. 如何?

谢谢!

4

2 回答 2

1

它实际上不起作用,您需要使用运算符'&'的地址将值存储在数组中。

scanf("%f", &timerunner1[x]);

此外,您的数组不够大,无法存储循环所需的 6 个整数,并且数组的下标从零开始,到 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;
}

此外,此代码仅适用于正值,因为最大值被初始化为零并且始终大于任何负值,如果您需要负值,您应该能够进行实验并弄清楚这一点。

于 2012-10-07T23:19:07.067 回答
1

好的,在这个程序中,您必须手动加载每个玩家的时间。

/* 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;
}
于 2012-10-07T23:31:35.583 回答