输入3~5名学生的5门课的成绩,求①每个学生的平均成绩②每门课的平均成绩③每门课的最高成绩要求:1.只定义一个有参函数,计算并输出学生的平均成绩,该函数还兼具求②③功能2.用到全局变量或静态局部变量
时间: 2024-02-21 21:01:27 浏览: 17
好的,我理解了你的问题。下面是代码实现:
```python
#include <stdio.h>
#define MAX_STUDENT 5
#define MAX_COURSE 5
static float courseSum[MAX_COURSE] = {0}; // 每门课的总成绩
static int courseMax[MAX_COURSE] = {0}; // 每门课的最高成绩
static int studentCount = 0; // 学生数量
void calculateStudentAverage(float scores[]) {
float sum = 0;
int max = 0;
for (int i = 0; i < MAX_COURSE; i++) {
sum += scores[i];
courseSum[i] += scores[i];
if (scores[i] > courseMax[i]) {
courseMax[i] = scores[i];
}
if (scores[i] > max) {
max = scores[i];
}
}
float average = sum / MAX_COURSE;
printf("平均分:%.2f\n", average);
printf("最高分:%d\n", max);
studentCount++;
}
void printCourseAverage() {
printf("每门课的平均分:\n");
for (int i = 0; i < MAX_COURSE; i++) {
float average = courseSum[i] / studentCount;
printf("课程%d:%.2f\n", i+1, average);
}
}
void printCourseMax() {
printf("每门课的最高分:\n");
for (int i = 0; i < MAX_COURSE; i++) {
printf("课程%d:%d\n", i+1, courseMax[i]);
}
}
int main() {
float scores[MAX_COURSE];
for (int i = 0; i < MAX_STUDENT; i++) {
printf("请输入第%d个学生的成绩:\n", i+1);
for (int j = 0; j < MAX_COURSE; j++) {
scanf("%f", &scores[j]);
}
calculateStudentAverage(scores);
}
printCourseAverage();
printCourseMax();
return 0;
}
```
这个程序中,我们定义了一个静态局部变量 `courseSum` 和一个静态局部变量 `courseMax`,用来分别记录每门课的总成绩和最高成绩。每次调用 `calculateStudentAverage` 函数时,会更新这两个变量。在程序结束时,我们可以调用 `printCourseAverage` 和 `printCourseMax` 函数,输出每门课的平均成绩和最高成绩。
需要注意的是,我们在 `calculateStudentAverage` 函数中还记录了学生的数量 `studentCount`,这个变量用来计算每门课的平均成绩。由于这个变量需要在多个函数中使用,我们也将其定义为静态局部变量。