给定N个学生的基本信息,每个学生基本信息包括学号(由10个数字组成的字符串)、姓名(长度小于10的不包含空白字符的非空字符串)和2门课程的成绩([0,100]区间内的整数),按照总分从高到低进行排序,并将排序后的结果写入文件test.txt。C语言
时间: 2024-02-11 09:09:16 浏览: 87
可以使用结构体来存储每个学生的基本信息,并使用qsort函数进行排序。以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char id[11]; // 学号
char name[11]; // 姓名
int score1; // 第一门课成绩
int score2; // 第二门课成绩
int total; // 总分
} Student;
int cmp(const void *a, const void *b) {
Student *s1 = (Student *)a;
Student *s2 = (Student *)b;
if (s1->total != s2->total) {
return s2->total - s1->total; // 按照总分从高到低排序
} else { // 如果总分相同,则按照学号从小到大排序
return strcmp(s1->id, s2->id);
}
}
int main() {
int n;
scanf("%d", &n);
Student *students = (Student *)malloc(sizeof(Student) * n);
for (int i = 0; i < n; i++) {
scanf("%s %s %d %d", students[i].id, students[i].name, &students[i].score1, &students[i].score2);
students[i].total = students[i].score1 + students[i].score2;
}
qsort(students, n, sizeof(Student), cmp); // 排序
FILE *fp = fopen("test.txt", "w");
for (int i = 0; i < n; i++) {
fprintf(fp, "%s %s %d %d %d\n", students[i].id, students[i].name, students[i].score1, students[i].score2, students[i].total);
}
fclose(fp);
free(students);
return 0;
}
```
在上面的代码中,cmp函数用于比较两个学生的大小关系。qsort函数调用该函数进行排序。最后将排序后的结果写入文件test.txt中。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)