C语言,学生成绩结构体数组,按照学生成绩顺序重新排列数组
时间: 2023-10-29 19:15:50 浏览: 41
可以使用C语言的qsort函数来实现结构体数组按照学生成绩排序的功能。
首先,定义一个结构体类型,包括学生姓名和成绩:
```c
struct student {
char name[20];
float score;
};
```
然后,定义一个结构体数组,存储学生的信息:
```c
struct student stu[5] = {
{"Tom", 85.5},
{"Jerry", 77.0},
{"Mike", 92.5},
{"Lucy", 66.5},
{"Lily", 88.0}
};
```
接下来,编写比较函数,用于在qsort函数中进行比较:
```c
int cmp(const void *a, const void *b) {
return ((struct student *)a)->score - ((struct student *)b)->score;
}
```
最后,调用qsort函数对数组进行排序:
```c
qsort(stu, 5, sizeof(struct student), cmp);
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
float score;
};
int cmp(const void *a, const void *b) {
return ((struct student *)a)->score - ((struct student *)b)->score;
}
int main() {
struct student stu[5] = {
{"Tom", 85.5},
{"Jerry", 77.0},
{"Mike", 92.5},
{"Lucy", 66.5},
{"Lily", 88.0}
};
qsort(stu, 5, sizeof(struct student), cmp);
for (int i = 0; i < 5; i++) {
printf("%s %.1f\n", stu[i].name, stu[i].score);
}
return 0;
}
```
输出结果:
```
Lucy 66.5
Jerry 77.0
Tom 85.5
Lily 88.0
Mike 92.5
```