2017-02-05 1 views
2
#include <stdio.h> 
int main(void) 
{ 
int file, i, total, min, max, num; 
float avg; 
int scores[1000]; 
int morescores[1000]; 
min = 10000000; 
max = -10000000; 


FILE *afile; 
afile = fopen("scores.txt", "r"); 

i=0; 
while(fscanf(afile, "%d", &num) != EOF) { 
    i++; 
    } 
    printf("The number of values in scores.txt is %d\n", i); 

//so we know there are 35 values in this file 

fclose(afile); 


afile = fopen("scores.txt", "r"); 
i=total=0; 
while(fscanf(afile, "%d", &scores[i]) != EOF) { 
    i++; 
    total += scores[i]; 

    avg = total/i; 

    if (scores[i] < min) { 
    min = scores[i]; 
    } else if (scores[i] > max) { 
    max = scores[i]; 
    } 
} 
    printf("The total of the integers is %d.\n", total); 
    printf("The number of integers in the file is %d.\n", i); 
    printf("The average of the integers is %f.\n", avg); 
    printf ("The minimum is %d.\n", min); 
    printf ("The maximum is %d.\n", max);  


    fclose(afile); 
    return (0); 
} 

ファイルscores.txtからすべての値を読み込み、これらの値を使用して数式を実行しようとしています。私はファイル内の特定の値を呼び出すときに何をするのか分からない。私は数式[i]を式に入力するとうまくいかない。助言がありますか?ファイルから配列に読み込まれる値を含む簡単な計算

+0

「は動作しません」の意味は何ですか? avgはループ外で計算されることがあります。 – Aubin

+0

印刷された値は巨大でランダムなものです。合計で+ =スコア[i]の部分スコアの代わりに何を入れますか[i] –

答えて

1

あなたは、ループの最後でi

while(fscanf(afile, "%d", &scores[i]) != EOF) { 
    i++; 

の増分を移動する必要があります:あなたはscores[n]に値を格納し、scores[n+1]を使用しているため

while(fscanf(afile, "%d", &scores[i]) != EOF) { 
    ... 
    i++; 
} 

...

コード:

#include <stdio.h> 

int main(void) { 
    int num; 
    float avg; 
    int scores[1000]; 
    int morescores[1000]; 
    int min = 10000000; 
    int max = -10000000; 
    FILE * afile = fopen("scores.txt", "r"); 
    if(! afile) { 
     perror("scores.txt"); 
     return 1; 
    } 
    int i = 0; 
    while(fscanf(afile, "%d", &num) != EOF) { 
     i++; 
    } 
    printf("The number of values in scores.txt is %d\n", i); 
    fclose(afile); 
    afile = fopen("scores.txt", "r"); 
    int total = 0; 
    i = 0; 
    while(fscanf(afile, "%d", &(scores[i])) != EOF) { 
     total += scores[i]; 
     if (scores[i] < min) { 
     min = scores[i]; 
     } 
     else if (scores[i] > max) { 
     max = scores[i]; 
     } 
     i++; 
    } 
    avg = total/i; 
    printf("The total of the integers is %d.\n", total); 
    printf("The number of integers in the file is %d.\n", i); 
    printf("The average of the integers is %f.\n", avg); 
    printf("The minimum is %d.\n", min); 
    printf("The maximum is %d.\n", max); 
    fclose(afile); 
    return 0; 
} 

と実行は次のようになります。

[email protected] ~/Dev/C $ echo 1 2 3 4 5 6 7 8 9 10 > scores.txt 
[email protected] ~/Dev/C $ gcc minMax.c -o MinMax 
[email protected] ~/Dev/C $ ./MinMax 
The number of values in scores.txt is 10 
The total of the integers is 55. 
The number of integers in the file is 10. 
The average of the integers is 5.000000. 
The minimum is 1. 
The maximum is 10. 
[email protected] ~/Dev/C $ 
関連する問題