在C語言中,使用for循環計算平均成績的方法如下:
#include<stdio.h>
const int NUMBER_OF_STUDENTS = 5;
int scores[NUMBER_OF_STUDENTS];
for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
printf("請輸入第%d個學生的成績: ", i + 1);
scanf("%d", &scores[i]);
}
int sum = 0;
float average = 0.0;
for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
sum += scores[i];
}
average = (float)sum / NUMBER_OF_STUDENTS;
printf("平均成績為: %.2f\n", average);
將以上代碼片段組合在一起,完整的C語言程序如下:
#include<stdio.h>
const int NUMBER_OF_STUDENTS = 5;
int main() {
int scores[NUMBER_OF_STUDENTS];
for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
printf("請輸入第%d個學生的成績: ", i + 1);
scanf("%d", &scores[i]);
}
int sum = 0;
float average = 0.0;
for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
sum += scores[i];
}
average = (float)sum / NUMBER_OF_STUDENTS;
printf("平均成績為: %.2f\n", average);
return 0;
}
運行此程序后,根據提示輸入每個學生的成績,程序將計算并輸出平均成績。