通讯录排序

程序要求:通讯录的结构记录包括姓名、生日、电话号码,其中生日包括年、月和日这三项。定义一个嵌套的结构类型,输入你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);

       }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值