ANSI C - 数组中的更高元素

时间:2012-10-07 23:09:31

标签: c arrays numbers ansi

我的代码遇到了一些问题,要在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 ..如何?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

scanf(“%f”,&amp; 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;
}

此外,此代码仅适用于正值,因为最大值初始化为零并且总是大于任何负值,如果您需要负值,您应该能够体验并弄明白。

答案 1 :(得分: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;
}