//2025年-第4题机构体母题分析:
//有n个结构体变量,内含学号,姓名和三门课程成绩。
//要求输出平均成绩最高的学生信息(包括学号、姓名、3科成绩和平均成绩)
#include<stdio.h>
#define N 3//本题设置学生N=3
//声明结构体
struct Student
{
int num;
char name[20];
float score[3];
float aver;
};
//方法input:接受数据计算平均值
//因为struct Student stu[N],*p=stu;
//相当申请的全局变量,所以不需要返回值所以用Void,即可完成结构体数组的修改
void input(struct Student stu[]) {
printf_s("请输入学号,姓名和三门课程成绩\n");
for(int i =0;i<N;i++){
scanf_s("%d %s %f %f %f", &stu[i].num, stu[i].name,sizeof(stu[i].name),
&stu[i].score[0] ,& stu[i].score[1], & stu[i].score[2]);
stu[i].aver = (stu[i].score[0] +stu[i].score[1] + stu[i].score[2]) / 3.0;//3.0注意float
}
}
//方法 max:找平均值最高的学生
struct Student max(struct Student stu[]) {
//遍历学生结构体数组的平均分取最大值
int i,m = 0;
//i为该方法作用域内的全局变量否则取不到下标
for (i = 0; i < N; i ++ ) {
if (stu[i].aver > stu[m].aver) {
m = i;
}
}
//对比后m作为对比后的下标统一输出
//**注此句放在循环外**
return stu[m];
}
//方法print:负责打印最高的学生
//注意此处不用struct Student stu[],
//数组因为接收单个加工好的一个结构体信息,当然也可以传数组但是对应最大值的,
//下标还要一起传过来解析
void print(struct Student stu) {
printf_s("\n成绩最高的学生是:\n");
printf_s("学号:%d \n", stu.num);
printf_s("姓名:%s \n", stu.name);
printf_s("三科成绩:%5.1f,%5.1f,%5.1f\n", stu.score[0], stu.score[1], stu.score[2]);
printf_s("三科平均成绩:%6.1f\n", stu.aver);
}
//方法main:主函数负责全局调用
int main() {
//三个函数声明
void input(struct Student stu[]);
struct Student max(struct Student stu[]);
void print(struct Student stu);
//结构体的声明
struct Student stu[N],*p=stu;
//*p为指针即地址,而p为指针变量可以储存地址,将地址储存到指针变量P中,就叫做P指向谁,
//函数调用
input(p);//input(stu);也可以
print(max(p));
system("pause");
return 0;
}
//运行结果
请输入学号,姓名和三门课程成绩
101 UZI 99 80 88
102 Jack 80 80 80
103 NING 10 20 30
成绩最高的学生是:
学号:101
姓名:UZI
三科成绩: 99.0, 80.0, 88.0
三科平均成绩: 89.0
请按任意键继续. . .
//运行结果
2025年-第4题机构体母体分析
于 2024-11-26 23:36:54 首次发布