结构体变量的引用

 输入10个同学的姓名、数学成绩、英语成绩和物理成绩,确定总分最高的同学,并打印其姓名及其三门课程的成绩。
#include "stdio.h"
struct Student /*定义结构体struct Student*/
{
char Name[20]; /*姓名*/
float Math; /*数学*/
float English; /*英语*/
float Physical; /*物理*/
};
void main()
{
struct Student oStu;
struct Student oMaxStu;
int i;
float fMaxScore;
float fTotal;
printf("/nPlease input 10 students and there score/n");/*提示信息*/
printf("----------------------------------------/n");
printf("Name Math English Physical /n");
printf("----------------------------------------/n");
fMaxScore=0;
for(i=0;i<10;i++)
{
/*读入当前同学的相关信息*/
scanf("%s %f %f %f",
oStu.Name,&oStu.Math,&oStu.English,&oStu.Physical);
fTotal=oStu.Math+oStu.English+oStu.Physical;
if(fMaxScore<fTotal)
{
strcpy(oMaxStu.Name,oStu.Name);
oMaxStu.Math=oStu.Math;
oMaxStu.English=oStu.English;
oMaxStu.Physical=oStu.Physical;
}
}
printf("----------------------------------------/n");
print("%s %f %f %f",
oMaxStu.Name,oMaxStu.Math,oMaxStu.English,oMaxStu.Physical);
}
运行结果如下:
Please input 10 students and there score
----------------------------------------
Name,Math,English,Physical
---------------------------------------
Liming 80 96.5 79.5
LiuHai 86 86.5 86.5
……
---------------------------------------
Liming 80 96.5 79.5
其中从键盘上输入结构体变量方法为
scanf("%s %f %f %f",oStu.Name,&oStu.Math,&oStu.English,&oStu.Physical);
保存当前最高分同学的信息的语句如下:
if(fMaxScore<fTotal)
{
strcpy(oMaxStu.Name,oStu.Name);
oMaxStu.Math=oStu.Math;
oMaxStu.English=oStu.English;
oMaxStu.Physical=oStu.Physical;
}
分别将结构体变量oStu 的信息复制到oMaxStu的方法,为分别复制结构体变量的各个成员变量。
另外也可以将一个结构体变量作为一个整体进行拷贝和赋值,但是只限于作为函数参数传递或作为函数的返回值返回。例如:
/*函数定义*/
struct Point MidPoint( struct Point oP1, struct Point oP2)
{
struct Point oTemp;
oTemp.x= (oP1.x+ oP2.x)/2;
oTemp.y= (oP1.y+ oP2.y)/2;
oTemp.z= (oP1.z+ oP2.z)/2;
/*函数返回值*/
return oTemp;
}
void main()
{
struct Point oP1={0.0,0.2,0.3};
struct Point oP2={1.2,0.2,0.3};
struct Point oMid;
/*函数调用*/
oMid= MidPoint(oP1, oP2);
}
其中struct Point MidPoint( struct Point oP1, struct Point oP2)函数的返回值类型为struct Point,函数的形式参数为struct Point oP1, struct Point oP2。在main()函数中,函数的调用形式如下:
oMid= MidPoint(oP1, oP2);
首先将实际参数oP1和oP2分别作为整体拷贝给函数的形式参数struct Point oP1和struct Point oP2,函数计算完毕,将计算结果通过函数的返回值带回主调函数main(),并将函数的返回值拷贝给变量struct Point oMid。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值