有5个学生,每个学生有3门课程的成绩,从键盘输入以上数据(包括学号、姓名、3门课程成绩),计算出平均成绩,将原有数据和计算出的平均分数存放在磁盘文件stud中。
设5名学生的学号、姓名和3门课程成绩如下:
99101 Wang 89,98,67.5
99103 Li 60,80,90
99106 Fun 75.5,91.5,99
99110 Ling 100,50,62.5
99113 Yuan 58,68,71
在向文件stud写入数据后,应检查验证stud文件中的内容是否正确。
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)// 定义学生结构体
typedef struct Student {int id;char name[20];double scores[3];double average;
} Student;// 计算平均成绩
void calculateAverage(Student* s) {s->average = (s->scores[0] + s->scores[1] + s->scores[2]) / 3;
}// 将学生数据写入文件
void writeToFile(Student* students, int num) {FILE* fp;fp = fopen("stud", "w");if (fp == NULL) {perror("Error opening file");exit(1);}for (int i = 0; i < num; i++) {fprintf(fp, "%d %s %.1lf %.1lf %.1lf %.2lf\n", students[i].id, students[i].name,students[i].scores[0], students[i].scores[1], students[i].scores[2], students[i].average);}fclose(fp);
}// 从文件读取数据并验证
void readAndVerify() {FILE* fp;fp = fopen("stud", "r");if (fp == NULL) {perror("Error opening file");exit(1);}Student s;while (fscanf(fp, "%d %s %lf %lf %lf %lf", &s.id, s.name, &s.scores[0], &s.scores[1], &s.scores[2], &s.average) == 6) {double calculatedAverage = (s.scores[0] + s.scores[1] + s.scores[2]) / 3;if (calculatedAverage != s.average) {printf("Error: Incorrect average for student %s\n", s.name);}else {printf("Data for student %s is correct\n", s.name);}}fclose(fp);
}int main() {Student students[5];// 输入学生数据for (int i = 0; i < 5; i++) {scanf_s("%d %s %lf %lf %lf", &students[i].id, students[i].name, &students[i].scores[0], &students[i].scores[1], &students[i].scores[2]);calculateAverage(&students[i]);}// 将数据写入文件writeToFile(students, 5);// 从文件读取并验证readAndVerify();return 0;
}