程序中已经定义好结构体并初始化结构体数组,函数fun的功能是:找出成绩最高的学生记录,通过结构体形参返回主函数。已知只有一个最高分。 main函数及函数头部不要做任何修改。
时间: 2023-06-19 18:07:33 浏览: 58
下面是可能的实现:
```c
#include <stdio.h>
#define MAX_N 100
typedef struct {
char name[20];
int score;
} Student;
void fun(Student stu[], int n, Student *max_score_student) {
*max_score_student = stu[0];
for (int i = 1; i < n; i++) {
if (stu[i].score > max_score_student->score) {
*max_score_student = stu[i];
}
}
}
int main() {
int n;
Student stu[MAX_N];
printf("Please input the number of students: ");
scanf("%d", &n);
printf("Please input the name and score of each student:\n");
for (int i = 0; i < n; i++) {
scanf("%s%d", stu[i].name, &stu[i].score);
}
Student max_score_student;
fun(stu, n, &max_score_student);
printf("The student with the highest score is: %s %d\n", max_score_student.name, max_score_student.score);
return 0;
}
```
在上述代码中,`fun` 函数通过指针参数返回最高分的学生记录,而不是通过返回值。这种方式可以避免结构体作为返回值时的复制操作,提高效率。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)