编写一段C语言,要求如下 输入n个朋友的信息,包括姓名、生日、电话号码,本题要求编写程序,按照年龄从大到小的顺序依次输出通讯录。题目保证所有人的生日均不相同。 输入格式: 输入第一行给出正整数n(<10)。随后n行,每行按照“姓名 生日 电话号码”的格式给出一位朋友的信息,其中“姓名”是长度不超过10的英文字母组成的字符串,“生日”是年月日格式的日期,“电话号码”是不超过17位的数字及+、-组成的字符串。 输出格式: 按照年龄从大到小输出朋友的信息,格式同输出。 输入样例: 3 zhang 19850403 13912345678 wang 19821020 +86-0571-88018448 qian 19840619 13609876543 输出样例: wang 19821020 +86-0571-88018448 qian 19840619 13609876543 zhang 19850403 13912345678
时间: 2023-06-25 11:06:53 浏览: 59
以下是一份简单的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct friend_info {
char name[11];
char birthday[9];
char phone[18];
};
int compare_birthday(const void* a, const void* b) {
struct friend_info* fa = (struct friend_info*)a;
struct friend_info* fb = (struct friend_info*)b;
return strcmp(fa->birthday, fb->birthday);
}
int main() {
int n;
scanf("%d", &n);
struct friend_info* friends = (struct friend_info*)malloc(n * sizeof(struct friend_info));
for (int i = 0; i < n; i++) {
scanf("%s %s %s", friends[i].name, friends[i].birthday, friends[i].phone);
}
qsort(friends, n, sizeof(struct friend_info), compare_birthday);
for (int i = n - 1; i >= 0; i--) {
printf("%s %s %s\n", friends[i].name, friends[i].birthday, friends[i].phone);
}
free(friends);
return 0;
}
```
题目要求按照年龄从大到小的顺序依次输出通讯录,我们可以先将所有朋友的信息按照生日从小到大排序,然后再从大到小输出。由于输入的生日是年月日格式的日期,我们可以直接使用 `strcmp()` 进行比较。由于 `qsort()` 函数需要传入一个比较函数,我们定义了 `compare_birthday()` 函数来比较两个朋友的生日,然后将其传入 `qsort()` 函数中进行排序。最后,我们按照倒序输出每个朋友的信息即可。
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)