我需要写一个c语言代码,它的要求是:在主函数中输入n及n个学生的信息(包括学号,姓名,成绩),调用函数按照成绩从高到低的顺序进行排序,最后在主函数中输出排序后的学生信息。
时间: 2024-03-26 13:34:45 浏览: 64
好的,我可以帮您写一个符合要求的 C 语言代码,以下是代码:
```c
#include <stdio.h>
#include <string.h>
struct student {
char id[10];
char name[20];
int score;
};
void sort(struct student stu[], int n);
int main() {
int n, i;
printf("请输入学生人数: ");
scanf("%d", &n);
struct student stu[n];
for (i = 0; i < n; i++) {
printf("请输入第%d个学生的信息: \n", i + 1);
printf("学号: ");
scanf("%s", stu[i].id);
printf("姓名: ");
scanf("%s", stu[i].name);
printf("成绩: ");
scanf("%d", &stu[i].score);
}
sort(stu, n);
printf("排序后的学生信息: \n");
for (i = 0; i < n; i++) {
printf("学号: %s, 姓名: %s, 成绩: %d\n", stu[i].id, stu[i].name, stu[i].score);
}
return 0;
}
void sort(struct student stu[], int n) {
int i, j;
struct student temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (stu[i].score < stu[j].score) {
temp = stu[i];
stu[i] = stu[j];
stu[j] = temp;
}
}
}
}
```
代码说明:
1. 在主函数中,先输入学生人数 n,并定义一个结构体数组 stu 存储学生信息。
2. 利用 for 循环输入每个学生的信息,包括学号、姓名、成绩。
3. 调用排序函数 sort 对结构体数组 stu 进行成绩从高到低的排序。
4. 利用 for 循环输出排序后的学生信息。
5. 排序函数 sort 中使用冒泡排序算法,比较相邻两个学生的成绩,将成绩高的交换到前面。
希望对您有所帮助!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)