输入n个朋友的信息,包括姓名、生日、电话号码,本题要求编写程序,按照年龄从大到小的顺序依次输出通讯录。题目保证所有人的生日均不相同。C语言
时间: 2023-06-16 22:07:53 浏览: 138
以下是一份实现此功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PHONE_NUM_LEN 12
#define MAX_FRIEND_NUM 100
typedef struct {
char name[MAX_NAME_LEN];
char birthday[9];
char phone_num[MAX_PHONE_NUM_LEN];
} Friend;
int compare_birthday(const void* p1, const void* p2) {
const Friend* f1 = (const Friend*)p1;
const Friend* f2 = (const Friend*)p2;
int year1 = atoi(f1->birthday);
int year2 = atoi(f2->birthday);
return year2 - year1;
}
int main() {
Friend friends[MAX_FRIEND_NUM];
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s %s %s", friends[i].name, friends[i].birthday, friends[i].phone_num);
}
qsort(friends, n, sizeof(Friend), compare_birthday);
for (int i = 0; i < n; i++) {
printf("%s %s %s\n", friends[i].name, friends[i].birthday, friends[i].phone_num);
}
return 0;
}
```
首先定义了一个结构体Friend,其中包含了姓名、生日和电话号码三个信息。然后定义了一个比较函数compare_birthday,用于按照年龄从大到小排序。这里我们只考虑了生日的年份,而没有考虑月份和日期,因为题目保证所有人的生日均不相同。接下来在主函数中读入n个朋友的信息,使用qsort函数按照年龄从大到小排序,最后按照顺序输出通讯录即可。
阅读全文