/*
结构体变量的使用
*/
#include "stdio.h"
#include "string.h"
struct date
{
int year;
int month;
int day;
};
struct student
{
char name[12];
int age;
float score;
struct date birthday; ///注意这个位置的结构体嵌套
};
float average(struct student *s1,struct student *s2); ///由于结构体本身所占用的空间以及自定义函数形参的调用规则
///不推荐使用结构体类型的变量作为自定义函数的形参,而使用结构体指针取代
void main()
{
struct student stu1={"LingMing",21,85,1990,12,25},stu2;
stu2.age=21;strcpy(stu2.name,"ZhangHong");
stu2.birthday.year=1990;
stu2.birthday.month=10;
stu2.birthday.day=26;
stu2.score=70;
printf("这两个学生的信息为:\n");
printf("%s %d %.0f %d %d %d\n",stu1.name,stu1.age,stu1.score,
stu1.birthday.year,stu1.birthday.month,stu1.birthday.day);
printf("%s %d %.0f %d %d %d\n",stu2.name,stu2.age,stu2.score,
stu2.birthday.year,stu2.birthday.month,stu2.birthday.day);
printf("这两个学生的平均成绩为:%.1f\n",average(&stu1,&stu2)); ///注意这个位置保留一位小数
}
float average(struct student *s1,struct student *s2)
{
float ave;
ave=(s1->score+s2->score)/2; ///用指针变量获得相应成员的值
return ave;
}
/*总结:
1.结构体的定义,结构体嵌套使用
2.结构体作为函数的形参,要使用指针形式 用指针变量获得相应成员的值
3.结构体赋初值,结构体的输出形式
4.结构体和字符串函数搭配使用:strcpy();
*/
结构体变量的使用
最新推荐文章于 2024-06-09 22:51:54 发布
本文讲解了如何在C语言中定义和使用结构体,包括结构体的嵌套和作为函数参数时使用指针。重点介绍了结构体变量初始化、输出和自定义函数average()的应用。通过实例说明了如何处理结构体内的日期信息和计算两个学生平均成绩。
8151

被折叠的 条评论
为什么被折叠?



