いくつかのファイルからデータを読み取り、それを配列にスキャンし、最終的に画面に 13 の名前を出力し、それぞれの隣に 4 つの数字と、それらの数字の後に一種の評価チャートの文字を表示するプログラムに取り組んでいます。
ただし、平均を計算する目的で使用している関数の1つに問題があります。1 つの生徒のテストのすべてのスコアを 1 つの値に結合し、それを 4 で割って平均を求め、その平均を別の配列の 1 つの要素に格納します。
関数呼び出しは次のとおりです。
avg(&scores, &average);
スコアと平均は次のように定義されます。
int scores[13][4];
float average[13];
スコアは次のループを使用して入力されています。
for(i=0; i<=13; i++)
{
for(j=0; j<=4; j++)
{
fscanf(score, "%d", &scores[i][j]);
}
}
fclose(score);
参考までに、使用されるファイルを開くステートメントは次のとおりです。
FILE *student, *score;
score = fopen("scores.dat", "r");
関数自体は次のようになります。
void avg(int *scores, float *average)
{
int total1 = scores[0][0] + scores[0][1] + scores[0][2] + scores[0][3];
int total2 = scores[1][0] + scores[1][1] + scores[1][2] + scores[1][3];
int total3 = scores[2][0] + scores[2][1] + scores[2][2] + scores[2][3];
int total4 = scores[3][0] + scores[3][1] + scores[3][2] + scores[3][3];
int total5 = scores[4][0] + scores[4][1] + scores[4][2] + scores[4][3];
int total6 = scores[5][0] + scores[5][1] + scores[5][2] + scores[5][3];
int total7 = scores[6][0] + scores[6][1] + scores[6][2] + scores[6][3];
int total8 = scores[7][0] + scores[7][1] + scores[7][2] + scores[7][3];
int total9 = scores[8][0] + scores[8][1] + scores[8][2] + scores[8][3];
int total10 = scores[9][0] + scores[9][1] + scores[9][2] + scores[9][3];
int total11 = scores[10][0] + scores[10][1] + scores[10][2] + scores[10][3];
int total12 = scores[11][0] + scores[11][1] + scores[11][2] + scores[11][3];
int total13= scores[12][0] + scores[12][1] + scores[12][2] + scores[12][3];
float avg1 = total1 / 4;
float avg2 = total2 / 4;
float avg3 = total3 / 4;
float avg4 = total4 / 4;
float avg5 = total5 / 4;
float avg6 = total6 / 4;
float avg7 = total7 / 4;
float avg8 = total8 / 4;
float avg9 = total9 / 4;
float avg10 = total10 / 4;
float avg11 = total11 / 4;
float avg12 = total12 / 4;
float avg13 = total13 / 4;
return;
}
まだ完全ではありません。配列に avg1-avg13 を割り当てるように関数に指示する必要があります。しかし、このエラーを修正したら、それに取り組みます。
プログラムをそのまま実行しようとすると、多くのエラーが発生しますが、それらはすべて基本的に同じです。
ghp11.c: In function 'avg':
ghp11.c:127: error: subscripted value is neither array nor pointer
正しく動作するように修正する方法が正確にはわかりません。4 つの配列値を 1 つの整数値に結合して、total1 などに格納しようとしています。それらを平均化して保存できるようにします。