解题思路:
- 定义一个结构体,其中包括学生学号、姓名和3门课程的成绩;
- 创建若干个结构体变量,并初始化;
- 定义一个函数,以结构体变量作为参数,用于计算平均成绩;
- 定义一个函数,以结构体指针作为参数,用于找到平均成绩最高的学生,输出该学生的信息;
以下是具体的代码实现:
#include <stdio.h>
#include <string.h>
#define MAX_STU_NUM 5
// 定义学生结构体
struct student {
char id[10];
char name[20];
double score[3]; // 具体成绩
double aver_score; // 平均成绩
};
// 计算某个学生的平均成绩
void calc_score(struct student *stu) {
double sum = 0;
for (int i = 0; i < 3; i++) {
sum += stu->score[i];
}
stu->aver_score = sum / 3;
}
// 找到平均成绩最高的学生
void find_max_score(struct student *stus, int num) {
double max_score = 0.0;
int index = 0;
for (int i = 0; i < num; i++) {
struct student stu = stus[i];
calc_score(&stu);
if (max_score < stu.aver_score) {
max_score = stu.aver_score;
index = i;
}
}
struct student max_stu = stus[index];
calc_score(&max_stu);
printf("平均成绩最高的学生信息如下:\n");
printf("学号:%s\n", max_stu.id);
printf("姓名:%s\n", max_stu.name);
printf("成绩:%lf, %lf, %lf\n", max_stu.score[0], max_stu.score[1], max_stu.score[2]);
printf("平均成绩:%lf\n", max_stu.aver_score);
}
int main(void) {
// 创建MAX_STU_NUM个学生结构体变量
struct student stus[MAX_STU_NUM] = {
{"001", "张三", {90, 80, 85}},
{"002", "李四", {75, 85, 65}},
{"003", "王五", {60, 50, 70}},
{"004", "赵六", {95, 90, 92}},
{"005", "孙七", {80, 88, 82}}
};
// 执行查找最高平均成绩学生的操作
find_max_score(stus, MAX_STU_NUM);
return 0;
}