程序中已经定义好结构体并初始化结构体数组,函数fun的功能是:找出成绩最高的学生记录,通过结构体形参返回主函数。已知只有一个最高分。 main函数及函数头部不要做任何修改。 用C语言实现
时间: 2024-02-27 10:57:56 浏览: 20
好的,以下是用 C 语言实现的代码:
```c
#include <stdio.h>
struct student {
char name[20];
int score;
};
void fun(struct student stu[], int n, struct student *max)
{
int i, max_score = stu[0].score, max_index = 0;
for (i = 1; i < n; i++) {
if (stu[i].score > max_score) {
max_score = stu[i].score;
max_index = i;
}
}
*max = stu[max_index];
}
int main()
{
struct student stu[] = {
{"Tom", 80},
{"Jack", 90},
{"Lucy", 85},
{"Mary", 88}
};
int n = 4;
struct student max;
fun(stu, n, &max);
printf("成绩最高的学生是%s,成绩为%d。\n", max.name, max.score);
return 0;
}
```
这个程序先定义了一个结构体 student,表示学生的姓名和成绩。然后定义了一个函数 fun,用来找出成绩最高的学生记录。在函数中,使用了一个 for 循环来遍历所有学生的成绩,找到最高分的学生记录。最后,通过结构体指针形参 max 返回成绩最高的学生记录。
在 main 函数中,我们定义了一个结构体数组 stu,表示所有学生的姓名和成绩。然后调用函数 fun,找到成绩最高的学生记录,并将其输出。