在主函数中输入n及n个学生的信息(包括学号,姓名,成绩),调用函数按照成绩从高到低的顺序进行排序,最后在主函数中输出排序后的学生信息。用c语言
时间: 2024-02-23 22:00:03 浏览: 45
好的,以下是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct {
char id[20];
char name[20];
int score;
} Student;
// 按成绩从高到低排序的比较函数
int cmp(const void *a, const void *b) {
const Student *sa = (const Student *)a;
const Student *sb = (const Student *)b;
return sb->score - sa->score;
}
int main() {
int n;
printf("请输入学生人数:");
scanf("%d", &n);
// 动态分配存储学生信息的数组
Student *students = (Student *)malloc(n * sizeof(Student));
// 读入学生信息
printf("请按照“学号 姓名 成绩”的格式依次输入每个学生的信息:\n");
for (int i = 0; i < n; i++) {
scanf("%s %s %d", students[i].id, students[i].name, &students[i].score);
}
// 按成绩排序
qsort(students, n, sizeof(Student), cmp);
// 输出排序后的学生信息
printf("按成绩从高到低排序后的学生信息如下:\n");
for (int i = 0; i < n; i++) {
printf("%s %s %d\n", students[i].id, students[i].name, students[i].score);
}
// 释放动态分配的内存
free(students);
return 0;
}
```
注意,这里使用了标准库函数 `qsort` 来进行排序,它的第二个参数是数组元素个数,第三个参数是每个元素的大小,第四个参数是比较函数。比较函数的返回值为正数表示第一个参数大于第二个参数,为负数表示小于,为0表示相等。在本例中,我们定义了一个按成绩从高到低排序的比较函数 `cmp`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)