C语言结构体变量和结构体变量的指针作函数参数例题

来源:互联网 发布:淘宝背景图片素材 编辑:程序博客网 时间:2024/05/22 07:41
将n个学生的数据表示为结构体变量,内含学生学号、姓名和三门课的成绩。要求输出平均成绩最高的学生的信息
(包括学号、姓名、3门课成绩和平均成绩)。



解题思路:将n个学生的数据表示为结构体数组(有n个元素)。按照功能函数化的思想,分别用3个函数来实现不同的功能:
(1)用input函数来输入数据和求各学生的平均成绩。
(2)用max函数来找平均数成绩最高的学生。
(3)用print函数来输出成绩最高的学生信息。



#include "stdio.h"#define N 3          //学生数3。struct Student    //建立结构体。{int num;char name[20];float score[3];float aver;};int main(){void input (struct Student stu[]);struct Student max(struct Student stu[]);void print(struct Student stu);struct Student stu[N],*p=stu;                //定义结构体数组和指针。input(p);print(max(p));                                //调用print函数,以max函数的返回值作为实参。return 0;}void input(struct Student stu[]){int i;printf("输入各学生信息:学号、姓名、三门课成绩:\n ");for(i=0;i<N;i++){scanf("%d %s %f %f %f",&stu[i].num,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;}}struct Student max(struct Student stu[]){int i,m=0;for(i=0;i<N;i++)if(stu[i].aver>stu[m].aver) m=i;                       //找出平均成绩最高的学生在数组中的序号。return stu[m];                                         //返回包含该生信息的结构元素。}void print(struct Student stu){printf("\n成绩最高的学生是:\n");printf("学号:%d\n 姓名:%s\n 三门课成绩:%5.1f,%5.1f,%5.1f\n 平均成绩:%6.2f\n",stu.num,stu.name,stu.score[0],stu.score[1],stu.score[2],stu.aver);}


阅读全文
0 0