这段代码哪里有问题呢?为什么输入学生成绩后只能得出最高分和平均成绩,不能得出最低分?
将max= a[0]. score和min= a[0].score,改到scanf的下一行!不然最大和最小值都不是输入的值哦!
不知道你这个问题是否已经解决, 如果还没有解决的话:问题描述:
在计算学生的平均成绩时,输入学生成绩后只能得出最高分和平均成绩,无法得出最低分。请问这段代码存在哪些问题?如何修改才能得出最低分?(请提供代码片段以及输入成绩的方式)
存在问题:
代码中只实现了求最高分和平均成绩的函数,未实现求最低分的函数,导致无法得出最低分。
代码片段:
#include <stdio.h>
float average(float score[], int n) { //求平均分
float sum = 0, avg = 0;
for (int i = 0; i < n; i++) {
sum += score[i];
}
avg = sum / n;
return avg;
}
float max(float score[], int n) { //求最高分
float max = score[0];
for (int i = 1; i < n; i++) {
if (score[i] > max) {
max = score[i];
}
}
return max;
}
int main() {
float score[5] = {88, 95, 79, 62, 76};
int n = 5;
printf("最高成绩为: %.1f\n", max(score, n));
printf("平均成绩为: %.1f\n", average(score, n));
return 0;
}
修改方案:
在代码中增加求最低分的函数即可。
代码片段:
float min(float score[], int n) { //求最低分
float min = score[0];
for (int i = 1; i < n; i++) {
if (score[i] < min) {
min = score[i];
}
}
return min;
}
int main() {
float score[5] = {88, 95, 79, 62, 76};
int n = 5;
printf("最高成绩为: %.1f\n", max(score, n));
printf("最低成绩为: %.1f\n", min(score, n)); //新增代码
printf("平均成绩为: %.1f\n", average(score, n));
return 0;
}