c语言分别按学号和总分进行排序
时间: 2024-02-14 16:07:45 浏览: 18
可以使用结构体来表示每个学生的信息,包括学号和总分。然后使用qsort函数进行排序。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_STUDENTS 100
typedef struct {
int id;
int total_score;
} Student;
int cmp_id(const void *a, const void *b) {
const Student *s1 = (const Student *)a;
const Student *s2 = (const Student *)b;
return s1->id - s2->id;
}
int cmp_total_score(const void *a, const void *b) {
const Student *s1 = (const Student *)a;
const Student *s2 = (const Student *)b;
return s2->total_score - s1->total_score;
}
int main() {
int n;
Student students[MAX_STUDENTS];
// 读入学生信息
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", &students[i].id, &students[i].total_score);
}
// 按学号排序
qsort(students, n, sizeof(Student), cmp_id);
printf("按学号排序:\n");
for (int i = 0; i < n; i++) {
printf("%d %d\n", students[i].id, students[i].total_score);
}
// 按总分排序
qsort(students, n, sizeof(Student), cmp_total_score);
printf("按总分排序:\n");
for (int i = 0; i < n; i++) {
printf("%d %d\n", students[i].id, students[i].total_score);
}
return 0;
}
```
在上面的代码中,我们首先定义了一个结构体`Student`,包括学号和总分两个成员变量。然后定义了两个比较函数`cmp_id`和`cmp_total_score`,分别按学号和总分进行比较。最后在`main`函数中,读入学生信息,先按学号排序输出,再按总分排序输出。