程序要求:通讯录的结构记录包括姓名、生日、电话号码,其中生日包括年、月和日这三项。定义一个嵌套的结构类型,输入你n(3<n<10)个联系人的信息,再按他们的年龄从大到小的顺序依次输出其信息。
完整代码块如下:
#include <stdio.h>
typedef struct date
{
int year;
int month;
int day;
}DATE;
typedef struct people
{
char peopleName[10];
DATE birthday;
long peopleID;
}PEOPLE;
void Inputscore(PEOPLE stu[],int n);
void Printscore(PEOPLE stu[],int n);
int main()
{
int n;
PEOPLE a[10];
printf("How many student? ");
scanf("%d",&n);
Inputscore(a,n);
Printscore(a,n);
return 0;
}
void Inputscore(PEOPLE stu[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Input record %d:\n",i+1);
scanf("%s",stu[i].peopleName);
scanf(" %ld",&stu[i].peopleID);
scanf("%d",&stu[i].birthday.year);
scanf("%d",&stu[i].birthday.month);
scanf("%d",&stu[i].birthday.day);
}
}
void Printscore(PEOPLE stu[],int n)
{
int i,j;
PEOPLE t;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(stu[j].birthday.year<stu[i].birthday.year)
{
t=stu[j];
stu[j]=stu[i];
stu[i]=t;
}
}
}
printf("\n");
for(i=0;i<n;i++)
{
printf("%10ld%8s%10d%4d%2d\n",stu[i].peopleID,stu[i].peopleName,stu[i].birthday.year,stu[i].birthday.month,stu[i].birthday.day);
}
}
首先我们根据题目要求,构建嵌套结构体,代码块如下:
typedef struct birthday
{
int year;
int month;
int day;
}DATE;
typedef struct people
{
char peopleName[10];
DATE birthday;
long peopleID;
}PEOPLE;
在主函数main中得到我们所需要的人数n:
int main()
{
int n;
PEOPLE a[10];
printf("How many student? ");
scanf("%d",&n);
Inputscore(a,n);
Printscore(a,n);
return 0;
}
接着我们调用函数Inputscore(),从键盘输入我们所需要的每个人的数据。
void Inputscore(PEOPLE stu[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Input record %d:\n",i+1);
scanf("%s",&stu[i].peopleName);
scanf(" %ld",&stu[i].peopleID);
scanf("%d",&stu[i].birthday.year);
scanf("%d",&stu[i].birthday.month);
scanf("%d",&stu[i].birthday.day);
}
}
最后我们在函数Printscore()中把每个人通过年龄从小到大进行排序,并完成输出操作:
void Printscore(PEOPLE stu[],int n)
{
int i,j;
PEOPLE t;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(stu[j].birthday.year<stu[i].birthday.year)
{
t=stu[j];
stu[j]=stu[i];
stu[i]=t;
}
}
}
printf("\n");
for(i=0;i<n;i++)
{
printf("%10ld%8s%2d%2d%2d\n",stu[i].peopleID,stu[i].peopleName,stu[i].birthday.year,stu[i].birthday.month,stu[i].birthday.day);
}
}