5个学生,3门成绩,输入信息,保存到文件

有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),计算出平均成绩,况原有的数据和计算出的平均分数存放在磁盘文件"stud"中。

#include <stdlib.h>
#include <stdio.h>

typedef struct
{
int id;
char name[20];
float math;
float chinese;
float english;
float average;
}Stu;

int main(void)
{
Stu stu[5];
int i;
for(i=0; i < 5; i++)
{
printf("Please input the ID, Name and scores of three courses\n");
scanf("%d %s %f %f %f",&(stu[i].id),&(stu[i].name),&(stu[i].math),&(stu[i].chinese),&(stu[i].english));//注意scanf的""中不能加\n
stu[i].average = (stu[i].math + stu[i].chinese + stu[i].english)/3;
printf("average is %f\n",stu[i].average);
}

FILE *fp;
if((fp = fopen("stud","w"))== NULL)
{
printf("error:cannot open file!\n");
exit(0);
}
for(i=0; i<5; i++)
{
fprintf(fp, "%d %s %f %f %f %f",stu[i].id,stu[i].name,stu[i].english,stu[i].chinese,stu[i].math,stu[i].average);
}
fclose(fp);

return 0;
}

 

posted @ 2018-09-23 21:10  星月当空  阅读(315)  评论(0编辑  收藏  举报