C语言程序统计成绩:从键盘输入5个学生的学号、姓名以及数学、语文和英语成绩,写到文本文件f3.txt 中,再从文件中取出数据,计算每个学生的总成绩和亚均分,并将结果显示在屏幕上。试编写相应程序。
时间: 2024-12-23 21:19:24 浏览: 3
在C语言中,你可以创建一个简单的程序来实现这个功能。首先,我们需要读取用户输入并将其写入文件,然后再次从文件中读取数据进行处理。以下是程序的基本结构:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义结构体存储学生信息
struct Student {
int id;
char name[20];
float math_score, chinese_score, english_score;
};
void write_to_file(struct Student students[], int size) {
FILE *file = fopen("f3.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return;
}
for (int i = 0; i < size; i++) {
fprintf(file, "%d %s %.2f %.2f %.2f\n",
students[i].id, students[i].name,
students[i].math_score, students[i].chinese_score, students[i].english_score);
}
fclose(file);
}
void read_and_calculate(char *filename) {
struct Student students[5]; // 假设最多有5个学生
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Error reading file.\n");
return;
}
// 读取文件内容
for (int i = 0; i < 5 && fscanf(file, "%d %[^ ] %.2f %.2f %.2f\n", &students[i].id, students[i].name, &students[i].math_score, &students[i].chinese_score, &students[i].english_score) == 5; i++) {}
// 计算总成绩和平均分
float total_scores[5] = {0};
float sum = 0;
for (int i = 0; i < 5; i++) {
total_scores[i] = students[i].math_score + students[i].chinese_score + students[i].english_score;
sum += total_scores[i];
}
float average_scores[5];
for (int i = 0; i < 5; i++) {
average_scores[i] = total_scores[i] / 3;
}
printf("Student\tTotal Score\tAverage Score\n");
for (int i = 0; i < 5; i++) {
printf("%d\t%.2f\t%.2f\n", students[i].id, total_scores[i], average_scores[i]);
}
fclose(file);
}
int main() {
// 用户输入部分略去
// 存储学生信息
struct Student *students = malloc(5 * sizeof(struct Student));
write_to_file(students, 5); // 写入文件
// 从文件中读取并计算结果
read_and_calculate("f3.txt");
free(students); // 释放内存
return 0;
}
```
阅读全文