在一个结构体数组中存有3个人的姓名和年龄,输出3个人中年龄居中者的姓名和年龄。 要求: ① 3个人的数据采用直接初始化的方式赋值。 ② 利用结构体指针实现处理过程。
时间: 2023-12-03 11:42:40 浏览: 37
以下是实现代码:
```c
#include <stdio.h>
struct Person {
char name[20];
int age;
};
int main() {
struct Person people[3] = {{"Tom", 20}, {"Jerry", 30}, {"Mike", 25}};
struct Person *p = people;
int max_age = p->age, min_age = p->age, mid_age = p->age;
struct Person *max_p = p, *min_p = p, *mid_p = p;
for (int i = 0; i < 3; i++) {
if ((p + i)->age > max_age) {
max_age = (p + i)->age;
max_p = p + i;
}
if ((p + i)->age < min_age) {
min_age = (p + i)->age;
min_p = p + i;
}
}
for (int i = 0; i < 3; i++) {
struct Person *temp = p + i;
if (temp != max_p && temp != min_p) {
mid_age = temp->age;
mid_p = temp;
}
}
printf("The person with middle age is %s and he/she is %d years old.\n", mid_p->name, mid_p->age);
return 0;
}
```
运行结果:
```
The person with middle age is Mike and he/she is 25 years old.
```
阅读全文