有10个学生,每个学生的数据包括姓名、成绩,用指针变量找出其中成绩最高的学生。
时间: 2023-12-15 13:09:44 浏览: 65
好的,这是一个常见的问题,可以定义一个结构体来存储学生的姓名和成绩,然后使用指针遍历所有学生的数据,找出成绩最高的学生。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[20];
int score;
};
int main() {
struct student students[10] = {
{"Tom", 85},
{"Jerry", 92},
{"Alice", 76},
{"Bob", 80},
{"David", 88},
{"Linda", 93},
{"John", 81},
{"Mary", 79},
{"Peter", 90},
{"Sandy", 87}
};
struct student *p = students;
struct student *max_student = students;
for (int i = 0; i < 10; i++) {
if (p->score > max_student->score) {
max_student = p;
}
p++;
}
printf("The student with the highest score is: %s, %d\n", max_student->name, max_student->score);
return 0;
}
```
输出结果为:
```
The student with the highest score is: Linda, 93
```
我们定义了一个结构体 `student`,其中包括了学生的姓名和成绩。然后我们定义了一个指向该结构体类型的指针变量 `p`,并初始化为指向数组 `students` 的第一个元素。我们还定义了一个指向学生成绩最高的学生的指针变量 `max_student`,初始值也为数组 `students` 的第一个元素。
接下来我们使用指针变量 `p` 遍历数组 `students`,逐个比较每个学生的成绩,如果当前学生的成绩比记录的成绩最高的学生的成绩还要高,就更新指针变量 `max_student`。最后输出成绩最高的学生的姓名和成绩。
希望这个示例代码可以帮助你理解如何使用指针变量遍历数组,并找出其中的最大值。