1. There are five students, each student has a 3 course results, the above data entered from the keyboard (including student number, name, score three classes),
calculate the average score, the original data and the calculated average scores stored in a disk file "stud" in.
#include<stdio.h>
#include<stdlib.h>
struct student {//定义一个结构体,里面包含的成员属性有学号、姓名、成绩、平均分
char num[10];
char name[5];
int score[3];
float avg;
} stu[5];
int main() {
int i,j,sum;
FILE *fp;
for(i=0; i<5; i++) {//通过循环输入每个学生的学号、姓名、成绩
printf("请输入第%d位学生学号:\n",(i+1));
scanf("%s",stu[i].num);
printf("请输入学生姓名:\n");
scanf("%s",stu[i].name);
sum = 0;
for(j=0; j<3; j++) {
printf("请输入第%d门科目成绩:\n",(j+1));
scanf("%d",&stu[i].score[j]);
sum +=stu[i].score[j];
}
stu[i].avg = sum / 3.0;
}
fp = fopen("E:\\stud.txt","w");
for(i=0; i<5; i++) {//在控制台上显示结果
printf("姓名:%s 学号:%s:",stu[i].name,stu[i].num);
for(j=0; j<3; j++) {
printf("学科%d成绩%d:",(j+1),stu[i].score[j]);
}
printf("平均分%.2f\n",stu[i].avg);
}
for(i=0; i<5; i++) { //将输入的数据以及平均分写入文件
fprintf(fp,"姓名:%s 学号:%s ",stu[i].name,stu[i].num);
for(j=0; j<3; j++) {
fprintf(fp,"学科%d成绩:%d ",(j+1),stu[i].score[j]);
}
fprintf(fp,"平均分%.2f\n",stu[i].avg);
fputc('\n',fp);//换行
}
fclose(fp);
}
Results are as follows:
(1) In the console displays the results
The data written to the file (2)