用C语言编写一个程序,利用循环输入10个学生的成绩,计算这10个成绩的平均分、最高分和最低分并输出计算结果。 还是用C语言编写,提高要求:加入成绩校验(成绩在0~100为合法),遇到非法数据提示重新输入,直至合法,然后计算。
时间: 2024-11-25 17:20:27 浏览: 142
在C语言中,我们可以编写一个程序来实现这个需求。首先,我们需要创建一个数组来存储成绩,并使用循环和条件语句来进行输入验证。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h> // 包含浮点数比较函数fabs()
#define MAX_STUDENTS 10
float calculate_average(float scores[], int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += scores[i];
}
return sum / n;
}
float find_max_min(float scores[], int n) {
float max = scores[0], min = scores[0];
for (int i = 1; i < n; i++) {
if (scores[i] > max) {
max = scores[i];
} else if (scores[i] < min) {
min = scores[i];
}
}
return max, min;
}
int main() {
float scores[MAX_STUDENTS];
int n = 0;
while (n < MAX_STUDENTS) { // 循环直到收集到10个有效成绩
printf("请输入第%d个学生的成绩 (0-100): ", n + 1);
float score;
if (scanf("%f", &score) != 1 || score < 0 || score > 100) { // 输入验证
printf("输入错误!成绩必须在0-100之间。\n");
clearerr(stdin); // 清除输入流的错误状态
continue;
}
scores[n++] = score;
}
float average = calculate_average(scores, n);
float max_score, min_score = find_max_min(scores, n);
printf("平均成绩: %.2f\n", average);
printf("最高分: %.2f\n", max_score);
printf("最低分: %.2f\n", min_score);
return 0;
}
```
在这个程序中,我们首先定义了一个学生分数数组和最大记录数。然后,通过`while`循环获取用户的输入,如果输入的值不在有效范围内,就提示用户重新输入。一旦输入了10个有效的成绩,就计算平均分、最高分和最低分并输出结果。
阅读全文
相关推荐


















