#include <stdio.h> #include <string.h> #include <stdlib.h> // 定义结构体类型 struct Student { char id[10]; // 学号 char name[20]; // 姓名 char gender[10]; // 性别 int chinese; // 语文成绩 int math; // 数学成绩 int english; // 英语成绩 }; // 初始化几个学生的基本信息 struct Student students[] = { {"1001", "张三", "Male", 80, 90, 85}, {"1002", "李四", "Female", 75, 85, 90}, {"1003", "王五", "Male", 90, 80, 95}, {"1004", "赵六", "Female", 85, 95, 80}, {"1005", "钱七", "Male", 95, 85, 90} }; int count=5; // 学生数量 编写一个函数,实现能根据其中一项成绩对学生排序
时间: 2023-07-19 10:18:50 浏览: 46
下面是一个根据语文成绩对学生排序的示例代码:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student {
char id[10]; // 学号
char name[20]; // 姓名
char gender[10]; // 性别
int chinese; // 语文成绩
int math; // 数学成绩
int english; // 英语成绩
};
struct Student students[] = {
{"1001", "张三", "Male", 80, 90, 85},
{"1002", "李四", "Female", 75, 85, 90},
{"1003", "王五", "Male", 90, 80, 95},
{"1004", "赵六", "Female", 85, 95, 80},
{"1005", "钱七", "Male", 95, 85, 90}
};
int count = 5; // 学生数量
// 根据语文成绩排序
void sortStudentsByChinese() {
struct Student temp;
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - 1 - i; j++) {
if (students[j].chinese < students[j + 1].chinese) {
temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
int main() {
sortStudentsByChinese();
for (int i = 0; i < count; i++) {
printf("学号:%s 姓名:%s 性别:%s 语文成绩:%d 数学成绩:%d 英语成绩:%d\n",
students[i].id, students[i].name, students[i].gender, students[i].chinese, students[i].math, students[i].english);
}
return 0;
}
```
这个示例代码中,我们定义了一个 sortStudentsByChinese() 函数,它使用了冒泡排序的算法,根据语文成绩对学生进行排序。在主函数中,我们先调用该函数,然后循环输出排好序的学生信息。