输入n个朋友的信息,包括姓名、生日、电话号码,本题要求编写程序,按照年龄从大到小的顺序依次输出通讯录。题目保证所有人的生日均不相同。C语言
时间: 2023-11-28 13:49:51 浏览: 143
以下是一个示例代码,可以实现输入n个朋友的信息,并按照年龄从大到小的顺序输出通讯录:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义一个结构体表示朋友的信息
typedef struct {
char name[20]; // 姓名
char birthday[10]; // 生日
char phone[12]; // 电话号码
int age; // 年龄
} Friend;
// 计算年龄
int getAge(char *birthday) {
int year, month, day;
sscanf(birthday, "%d-%d-%d", &year, &month, &day);
time_t now = time(NULL);
struct tm *tm_now = localtime(&now);
int age = tm_now->tm_year + 1900 - year;
if (tm_now->tm_mon + 1 < month || (tm_now->tm_mon + 1 == month && tm_now->tm_mday < day)) {
age--;
}
return age;
}
// 比较函数,用于排序
int cmp(const void *a, const void *b) {
Friend *pa = (Friend *) a;
Friend *pb = (Friend *) b;
return pb->age - pa->age;
}
int main() {
int n;
printf("请输入朋友个数:");
scanf("%d", &n);
Friend *friends = (Friend *) malloc(n * sizeof(Friend));
// 输入朋友信息
for (int i = 0; i < n; i++) {
printf("请输入第%d个朋友的信息:\n", i + 1);
printf("姓名:");
scanf("%s", friends[i].name);
printf("生日(格式为yyyy-mm-dd):");
scanf("%s", friends[i].birthday);
printf("电话号码:");
scanf("%s", friends[i].phone);
friends[i].age = getAge(friends[i].birthday);
}
// 按年龄从大到小排序
qsort(friends, n, sizeof(Friend), cmp);
// 输出通讯录
printf("通讯录按年龄从大到小排序如下:\n");
for (int i = 0; i < n; i++) {
printf("%s\t%s\t%s\t%d\n", friends[i].name, friends[i].birthday, friends[i].phone, friends[i].age);
}
free(friends);
return 0;
}
```
注意,该代码中使用了`time.h`库中的`time()`和`localtime()`函数来获取当前时间,因此需要在编译时加上`-lm`选项,例如:
```
gcc -o friends friends.c -lm
```