14.文件score.txt保存了学生的平时成绩和期末成绩,内容如下: 学号,平时成绩,期末成绩 9999180101,77,88 9999180102,91,85 9999180103,87,96 9999180104,70,68 9999180105,86,72 编写程序读取所有成绩,计算总评成绩(四舍五入到整数),其中总评成绩=平时成绩40%+期末成绩60%。最后按总评成绩降序排列后保存至一个新的文件内,文件内容应该如下:学号,平时成绩,期末成绩,总评成绩 9999180103,87,96,92 9999180102,91,85,87 9999180101,77,88,84 9999180105,86,72,78 9999180104,70,68,69
时间: 2023-09-05 09:11:03 浏览: 261
下面是一个实现上述功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_STUDENTS 100
// 定义学生结构体
typedef struct {
char id[11]; // 学号
int pscore; // 平时成绩
int fscore; // 期末成绩
int tscore; // 总评成绩
} Student;
// 读取文件中的学生信息
int read_students(Student *students, const char *filename) {
FILE *fp;
int count = 0;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s", filename);
exit(1);
}
// 逐行读取学生信息
while (fscanf(fp, "%[^,],%d,%d\n", students[count].id, &students[count].pscore, &students[count].fscore) != EOF) {
count++;
}
fclose(fp);
return count;
}
// 计算学生的总评成绩
void calculate_tscore(Student *students, int count) {
for (int i = 0; i < count; i++) {
students[i].tscore = (int)(students[i].pscore * 0.4 + students[i].fscore * 0.6 + 0.5);
}
}
// 按总评成绩降序排列
void sort_students(Student *students, int count) {
Student temp;
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (students[j].tscore > students[i].tscore) {
temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
// 将学生信息保存至文件
void save_students(Student *students, int count, const char *filename) {
FILE *fp;
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Failed to open file %s", filename);
exit(1);
}
// 将学生信息写入文件
fprintf(fp, "学号,平时成绩,期末成绩,总评成绩\n");
for (int i = 0; i < count; i++) {
fprintf(fp, "%s,%d,%d,%d\n", students[i].id, students[i].pscore, students[i].fscore, students[i].tscore);
}
fclose(fp);
}
int main() {
Student students[MAX_STUDENTS];
int count;
count = read_students(students, "score.txt");
calculate_tscore(students, count);
sort_students(students, count);
save_students(students, count, "result.txt");
return 0;
}
```
注:在读取文件时,使用了"%[^,]"这个格式字符串,表示读取除逗号之外的所有字符,避免了因为读取到逗号而出现错误的情况。
阅读全文