文件 score.txt 中存放若干同学的学号及高数、英语、C 语言 3 门课的成绩,格式如下: 1001 张晓莉 90 80 70 1002 赵 龙 85 78 80 1003 李大有 60 70 76 ....... 利用结构体编写程序,实现如下功能: ① 从 score.txt 中逐个读入每个同学的成绩,用一个函数实现; ② 计算每个同学平均分,用一个函数实现; ③ 成绩按平均分排序,用一个函数实现; ④ 屏幕输出结果并写入文件 score_avg.txt 中,用一个函数实现。 文件 score_avg.txt 中的记录应该为: 学号 姓名 高数 英语 C 语言 平均分 1002 赵 龙 85 78 80 81.00 1001 张晓莉 90 80 70 80.00 1003 李大有 60 70 76 68.67 ......
时间: 2024-03-05 10:49:34 浏览: 173
我已经提供了上一题的示例代码,如果你想要实现这个功能,可以参考上一题的答案。这里再给出一遍代码以供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 50
#define MAX_NUM 100
typedef struct {
char id[MAX_LEN];
char name[MAX_LEN];
float math;
float english;
float c_language;
float average;
} Student;
int read_student_info(Student *students, char *filename);
void calculate_average(Student *students, int num);
void sort_by_average(Student *students, int num);
void output_result(Student *students, int num, char *filename);
int main() {
Student students[MAX_NUM];
char filename[] = "score.txt";
char output_file[] = "score_avg.txt";
int num = read_student_info(students, filename);
if (num == -1) {
printf("Failed to read file: %s\n", filename);
return 1;
}
calculate_average(students, num);
sort_by_average(students, num);
output_result(students, num, output_file);
return 0;
}
int read_student_info(Student *students, char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
}
int num = 0;
while (!feof(fp) && num < MAX_NUM) {
fscanf(fp, "%s%s%f%f%f", students[num].id, students[num].name, &students[num].math, &students[num].english, &students[num].c_language);
num++;
}
fclose(fp);
return num;
}
void calculate_average(Student *students, int num) {
for (int i = 0; i < num; i++) {
students[i].average = (students[i].math + students[i].english + students[i].c_language) / 3;
}
}
void sort_by_average(Student *students, int num) {
for (int i = 0; i < num; i++) {
for (int j = i + 1; j < num; j++) {
if (students[i].average < students[j].average) {
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
void output_result(Student *students, int num, char *filename) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Failed to open file: %s\n", filename);
return;
}
fprintf(fp, "学号\t姓名\t高数\t英语\tC语言\t平均分\n");
for (int i = 0; i < num; i++) {
fprintf(fp, "%s\t%s\t%.2f\t%.2f\t%.2f\t%.2f\n", students[i].id, students[i].name, students[i].math, students[i].english, students[i].c_language, students[i].average);
printf("%s\t%s\t%.2f\t%.2f\t%.2f\t%.2f\n", students[i].id, students[i].name, students[i].math, students[i].english, students[i].c_language, students[i].average);
}
fclose(fp);
}
```
这个程序实现了从文件中读取学生信息,计算平均分,按平均分排序,以及将结果输出到文件和屏幕上的功能。你可以根据自己的需求进行修改。注意,这里的文件格式是以制表符分隔的,如果你的文件格式不同,需要相应地修改代码。
阅读全文