在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;
}
运行此程序后,根据提示输入每个学生的成绩,程序将计算并输出平均成绩。