#include <stdio.h>
struct datatype1
{
char b;
int a;
char c;
}s1;
struct datatype2
{
char b;
short a;
char c;
}s2;
struct datatype3
{
char b;
char c;
int a;
}s3;
struct stu
{
int num;
char name[20];
char sex;
float score;
}s4;
struct date
{
int year;
int month;
int day;
}s5;
struct student
{
int num;
char name[20];
char sex;
struct date birth;
float score;
}s6;
int main()
{
/*****输出上述六种结构体类型所占字节数*****/
/********** Begin **********/
printf("1:%d\n2:%d\n3:%d\n4:%d\n5:%d\n6:%d\n",sizeof(s1),sizeof(s2),sizeof(s3),sizeof(s4),sizeof(s5),sizeof(s6));
/********** End **********/
return 0;
}
第2关 结构体变量的定义及应用
#include<stdio.h>
#include<string.h>
struct date
{
int year;
int month;
int day;
};
struct stu
{
int num;
char name[20];
char sex;
struct date birth;
float score;
};
int main()
{
struct stu s1 = {10010,"zhangsan",'m',2000,5,4,84.5}, s2, s3;
/*****输入学生信息存放在变量s2中*****/
/********** Begin **********/
scanf("%d\n%s\n%c\n%d%d%d\n%f\n",&s2.num,s2.name,&s2.sex,&s2.birth.year,&s2.birth.month,&s2.birth.day,&s2.score);
/********** End **********/
/*****交换两个结构体变量s1和s2*****/
/********** Begin **********/
s3=s1;s1=s2;s2=s3;
/********** End **********/
/*****输出结构体变量s1和s2的成员*****/
/********** Begin **********/
printf("学号:%d\n姓名:%s\n性别:%c\n出生日期:%d年%d月%d日\n成绩:%.1f\n学号:%d\n姓名:%s\n性别:%c\n出生日期:%d年%d月%d日\n成绩:%.1f",s1.num,s1.name,s1.sex,s1.birth.year,s1.birth.month,s1.birth.day,s1.score,s2.num,s2.name,s2.sex,s2.birth.year,s2.birth.month,s2.birth.day,s2.score);
/********** End **********/
return 0;
}
第3关 定义一个结构类型变量(包括年、月、日),实现输入一个日期显示它是该年第几天
#include<stdio.h>
typedef struct date
{
int year;
int month;
int day;
}DATE;
int main()
{
/********** Begin **********/
int s,i;DATE b;
scanf("%d%d%d",&b.year,&b.month,&b.day);
int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
for(s=0,i=1;i<b.month;i++)
{
s+=a[i];
}
if(b.month>2&&(b.year%4==0&&b.year%100!=0||b.year%400==0))
{s++;}s+=b.day;
printf("它是%d年的第%d天",b.year,s);
/********** End **********/
return 0;
}
第4关 向函数传递结构体
#include<stdio.h>
#include<string.h>
typedef struct date
{ int year;
int month;
int day;
}DATE;
typedef struct student
{
int num;
char name[20];
char sex;
DATE birthday;
float score;
}STUDENT;
void input(STUDENT *s);
void output(STUDENT s);
/********** Begin **********/
void input(STUDENT *s)
{
scanf("%d",&(s->num));
scanf("%s", s->name);
scanf(" %c",&( (*s).sex));
scanf("%d%d%d",&s->birthday.year, &s->birthday.month, &s-> birthday.day);
scanf("%f",&(s-> score));
}
void output(STUDENT s)
{
printf("学号:%d\n姓名:%s\n性别:%c\n出生日期:%d年%d月%d日\n成绩:%.1f",s.num,s.name,s.sex,s.birthday.year,s.birthday.month,s.birthday.day,s.score);
}
main()
{
STUDENT s2;
input(&s2);
output(s2);
}
/********** End **********/