用结构体变量和结构体变量的指针做参数函数

来源:互联网 发布:元数据被拒绝 编辑:程序博客网 时间:2024/05/16 03:42

例题:

有n个结构体变量,内含学生学号、姓名和3门课程的成绩。要求输出平均成绩最高的学生的信息(包括学号、姓名、3门课程成绩和平均成绩)

代码实现

#include<stdio.h>#define N 3//学生数为3struct Student   <span style="white-space:pre"></span> //建立结构体类型{int num;//学号char name[20];<span style="white-space:pre"></span>//姓名float score[3];<span style="white-space:pre"></span>//科目分数float aver;//平均数};struct Student stu[N], *p = stu;   <span style="white-space:pre"></span> //定义结构体数组与指针int main(){void input(struct Student stu[]);    <span style="white-space:pre"></span>//函数声明struct Student max(struct Student stu[]);void printf(struct Student stu);input(p);//调用函数printf(max(p));return 0;}void input(struct Student stu[])<span style="white-space:pre"></span>//定义函数{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;<span style="white-space:pre"></span>//求平均成绩}}struct Student max(struct Student stu[])    <span style="white-space:pre"></span>//定义max函数{        //用m存放平均成绩最高的学生在数组中的序号int i, m = 0;for (i = 0; i < N; i++)if (stu[i].aver>stu[m].aver)    <span style="white-space:pre"></span>       //找出平均成绩最高的学生在数组中的序号m = i;return stu[m];      <span style="white-space:pre"></span>//返回包含该生信息的结构体元素}void printf(struct Student stu)      <span style="white-space:pre"></span>//定义printf函数{printf("成绩最高的学生是:\n");printf("\n%d\n%s\n%-7.2f%-7.2f%-7.2f\n%-702.2f\n", stu.num, stu.name, stu.score[0], stu.score[1], stu.score[2], stu.aver);}

1 0
原创粉丝点击