有10个学生,每个学生的数据包括学号、姓名、3门课程的成绩,从键盘输入10个学生数据,要求输出3门课程总平均成绩,以及最高分的学生的数据(包括学号、姓名、3门课程成绩、平均分数)。
#include <stdio.h>
typedef struct {
int num;
char name[20];
float score[3];
} Student;
void input(Student students[], int n) {
for (int i = 0; i < n; i++) {
printf("Enter num, name, scores for student %d: ", i + 1);
scanf("%d %s %f %f %f", &students[i].num, students[i].name,
&students[i].score[0], &students[i].score[1], &students[i].score[2]);
}
}
float calculateAverage(Student students[], int n) {
float total[3] = {0, 0, 0};
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
total[j] += students[i].score[j];
}
}
return (total[0] + total[1] + total[2]) / (3 * n);
}
Student findTopStudent(Student students[], int n) {
Student topStudent = students[0];
float topAverage = (students[0].score[0] + students[0].score[1] + students[0].score[2]) / 3;
for (int i = 1; i < n; i++) {
float average = (students[i].score[0] + students[i].score[1] + students[i].score[2]) / 3;
if (average > topAverage) {
topStudent = students[i];
topAverage = average;
}
}
return topStudent;
}
int main() {
Student students[10];
input(students, 10);
float average = calculateAverage(students, 10);
Student topStudent = findTopStudent(students, 10);
printf("The average score of 3 courses is: %.2f\n", average);
printf("The top student is: Num: %d, Name: %s, Scores: %.2f, %.2f, %.2f\n",
topStudent.num, topStudent.name, topStudent.score[0], topStudent.score[1], topStudent.score[2]);
return 0;
}
代码解释:
1. 定义结构体:定义一个结构体 `Student`,包含学号、姓名和一个存储三个成绩的数组。
2. 计算平均成绩:在主函数中,从键盘输入10个学生的数据,计算每门课程的总平均成绩。
3. 找出最高分:找出最高分的学生,打印其学号、姓名、三门课程的成绩和平均分。