-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

わかりました、このプログラムでは、各プレーヤーの時間を手動でロードする必要があります。

/* 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 に答える
1

It doesn't work actually, you need to use the address of operator '&' to store the value in the array.

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

Also, your array isn't large enough to store the 6 integers that your loop is requiring and subscripting of an array starts at zero and ends at 5 (for 6 elements).

You can then either have another loop AFTER reading all your values to calculate the maximum or calculate it on the fly as below:

#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;
}

Also, this code only works on positive values because maximum is initialised to zero and will always be larger than any negative value, if you need negative values, you should be able to experiement and figure that out.

于 2012-10-07T23:19:07.067 に答える