编写一个程序,接收终端输入的10个学生信息(姓名、身高和体重),并保存在结构类型的数组中,从中查找出身高最高和体重最重的学生,并输出对应的详细信息。要求将查找身高最高和体重最重的学生这一功能描述采用一个子函数进行封装,并给出编写子函数定义时参照的相关原则。
#include <stdio.h>
#define N 10
//定义student结构体
typedef struct
{
char name[20];
int height;
int weight;
}STUDENT;
void Found(STUDENT Stu[],int n,STUDENT *pMaxH,STUDENT *pMaxW);//声明子函数,根据函数定义原则3将函数头设为void
int main()
{
STUDENT stu[N],maxheight,maxweight;//maxheight,maxweight用来存储结果
int i=0;
for(i=0;i<N;i++)
{
fflush(stdin);//清空输入缓冲区,确保不影响后面的数据读取
printf("input stu[%d] Info[name, height, weight ]\n", i+1);
gets(stu[i].name);//调用gets函数读取字符串name
scanf("%d",&stu[i].height);
scanf("%d",&stu[i].weight);
}
Found(stu,N,&maxheight,&maxweight);//调用函数Found
printf("The maxheight Info[name=%s, height=%d, weight=%d]\n", maxheight.name, maxheight.height, maxheight.weight);
printf("The maxweight Info[name=%s, height=%d, weight=%d]\n", maxweight.name, maxweight.height, maxweight.weight);
}
/*
input:stu,N,&maxheight,&maxweight
output:&maxheight,&maxweight
通过函数定义原则7,通过结构指针来完成调用程序和子函数之前的参数传递,将函数头定义为viod
*/
void Found(STUDENT Stu[],int n,STUDENT *pMaxH,STUDENT *pMaxW)//通过结构指针向函数Found传递参数
{
int i;
*pMaxH=Stu[0];
*pMaxW=Stu[0];//初始化pMaxH和pMaxW
for(i=0;i<n;i++)
{
if(Stu[i].height>(pMaxH->height))
{
*pMaxH=Stu[i];
}
}//循环比较pMaxH和第i-1个Stu的height,若第i-1个Stu的height大于pMaxH,则将其赋值给pMax
for(i=0;i<n;i++)
{
if(Stu[i].weight>(pMaxW->weight))
{
*pMaxW=Stu[i];
}
}//循环比较pMaxW和第i-1个Stu的weight,若第i-1个Stu的height大于pMaxW,则将其赋值给pMaW
}
本题主要考察了结构类型定义与变量声明、输入数据和返回结果为结构类型的函数、通过结构指针向函数传递参数