有N个学生,每个学生的数据包括学号、姓名、3门课的成绩,从键盘输入N个学生的数据,要求打印出3门课的总平均成绩,以及最高分的学生的数据(包括学号、姓名、3门课成绩)
2
1 blue 90 80 70
b clan 80 70 60
85 75 65
1 blue 90 80 70
使用 int 类型存储平均分,导致结果会被截断为整数,而不是保留小数部分。应该使用 float 或 double 类型来保留小数。
此处是对代码的分析:
定义了一个名为 Student 的结构体,包含学生的学号、姓名和三门课程的成绩。
input(struct Student *student):用于输入一个学生的数据记录,通过指针传递一个 Student 结构体的地址,然后从标准输入中读取学生的学号、姓名以及三门课程的成绩。
print(struct Student student[], int N):用于打印一个学生的数据记录,通过传入一个学生数组和学生数量,计算出平均成绩最高的学生并打印其学号、姓名以及三门课程的成绩。
print2(struct Student student[], int N):用于打印所有学生某一门课程的平均成绩,通过传入学生数组和学生数量,计算出每门课程的平均成绩并打印。
主函数 main():
首先读取一个整数 N,表示学生的数量,声明了一个长度为 N 的学生数组 students,使用循环调用 input() 函数输入 N 条学生数据记录,调用 print2() 函数打印所有学生的平均成绩,调用 print() 函数打印平均成绩最高的学生的数据记录。
- #include
-
- // 结构体定义:学生数据记录
- struct Student {
- char id[20]; // 学号
- char name[50]; // 姓名
- float score1; // 第一科成绩
- float score2; // 第二科成绩
- float score3; // 第三科成绩
- };
-
- // 函数:输入一个学生的数据记录
- void input(struct Student *student) {
- scanf("%s %s %f %f %f", student->id, student->name, &student->score1, &student->score2, &student->score3);
- }
-
- // 函数:打印一个学生的数据记录
- void print(struct Student student[], int N) {
- int score0 = (student[0].score1 + student[0].score2 + student[0].score3) / 3;
- int score1 = score0; // 初始化最高分为第一个学生的平均分
- int n = 0; // 记录最高分的学生索引
- for (int i = 0; i < N; i++) {
- int score = (student[i].score1 + student[i].score2 + student[i].score3) / 3;
- if (score1 <= score) {
- score1 = score;
- n = i;
- }
- }
- printf("%s %s %.0f %.0f %.0f\n", student[n].id, student[n].name, student[n].score1, student[n].score2, student[n].score3);
- }
- void print2(struct Student student[], int N) {
- int ascore1 =0;
- int ascore2 = 0;
- int ascore3=0;
- for (int i = 0; i < N; i++) {
- ascore1 += student[i].score1;
- ascore2 += student[i].score2;
- ascore3 += student[i].score3;
- }
- printf("%d %d %d\n",ascore1/N,ascore2/N,ascore3/N);
- }
-
- int main() {
- int N;
- scanf("%d", &N);
- // 声明一个学生数组,用来存储 N 条学生数据记录
- struct Student students[N];
-
- // 输入 N 条学生数据记录
- for (int i = 0; i < N; i++) {
- input(&students[i]); // 调用输入函数,传入当前学生的地址
- }
- print2(students, N);
- // 输出 N 条学生数据记录
- print(students, N); // 调用输出函数,传入学生数组和学生数量
-
- return 0;
- }