用c语言给定N个学生的基本信息,每个学生基本信息包括学号(由10个数字组成的字符串)、姓名(长度小于10的不包含空白字符的非空字符串)和2门课程的成绩([0,100]区间内的整数),按照总分从高到低进行排序,并将排序后的结果写入文件test.txt。
时间: 2024-02-13 14:07:51 浏览: 79
C语言输入学生成绩,计算并输出这些学生的最低分、最高分、平均分。
好的,这是一个需要用到结构体和文件操作的问题。具体步骤如下:
1. 定义一个结构体,包含学号、姓名、两门课程的成绩和总分。
```c
typedef struct student {
char id[11];
char name[11];
int score1;
int score2;
int total;
} Student;
```
2. 读入学生信息,并计算总分。
```c
Student students[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;
}
```
3. 按照总分从高到低进行排序。
```c
qsort(students, N, sizeof(Student), cmp);
int cmp(const void* a, const void* b) {
return (((Student*)b)->total - ((Student*)a)->total);
}
```
4. 将排序后的结果写入文件test.txt。
```c
FILE* fp;
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);
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
typedef struct student {
char id[11];
char name[11];
int score1;
int score2;
int total;
} Student;
int cmp(const void* a, const void* b) {
return (((Student*)b)->total - ((Student*)a)->total);
}
int main() {
Student students[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;
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);
return 0;
}
```
阅读全文