用C语言输入4个学生3门课的成绩,分别用函数实现下列各项功能: 1)计算出每个学生的平均分;2)计算出每门课程的平均分;3)找出所有12个分数中最高分数所对应的学生和课程
时间: 2024-12-06 11:26:11 浏览: 7
在C语言中,我们可以设计一个结构体`Student`存储学生信息,同时用三个数组分别存储三门课的成绩。接下来,我会展示如何编写几个函数来实现这些功能。
```c
#include <stdio.h>
typedef struct {
char name[50];
float score[3]; // 学生的三科成绩
} Student;
void input_scores(Student* students, int num_students) {
for (int i = 0; i < num_students; i++) {
scanf("Name: %s", students[i].name);
for (int j = 0; j < 3; j++) {
scanf("%f", &students[i].score[j]);
}
}
}
float average_score(Student student) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += student.score[i];
}
return sum / 3;
}
float course_average(float scores[], int num_courses) {
float sum = 0;
for (int i = 0; i < num_courses; i++) {
sum += scores[i];
}
return sum / num_courses;
}
void find_highest_score(Student students[], int num_students) {
int max_index = 0;
float highest_score = students[0].score[0];
for (int i = 1; i < num_students; i++) {
for (int j = 0; j < 3; j++) {
if (students[i].score[j] > highest_score) {
highest_score = students[i].score[j];
max_index = i;
}
}
}
printf("Highest score is %.2f, achieved by student %s in Course %d.\n",
highest_score, students[max_index].name, max_index % 3 + 1); // 课程编号从1开始
}
int main() {
int num_students = 4;
Student students[num_students];
input_scores(students, num_students);
printf("Average scores of each student:\n");
for (int i = 0; i < num_students; i++) {
printf("%s: %.2f\n", students[i].name, average_score(students[i]));
}
printf("Average scores of each course:\n");
float course_scores[3] = {students[0].score[0], students[1].score[1], students[2].score[2]};
printf("Course 1: %.2f\nCourse 2: %.2f\nCourse 3: %.2f\n", course_average(course_scores, 3));
find_highest_score(students, num_students);
return 0;
}
```
上述代码实现了所需的功能,包括输入学生成绩、计算平均分、课程平均分以及找出最高分及其对应的课程。请注意,课程编号在这里是按数组索引(1, 2, 3)表示的。
阅读全文