有五个学生,每个学生有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
");
scanf("%d %s %f %f %f",&(stu[i].id),&(stu[i].name),&(stu[i].math),&(stu[i].chinese),&(stu[i].english));//注意scanf的""中不能加
stu[i].average = (stu[i].math + stu[i].chinese + stu[i].english)/3;
printf("average is %f
",stu[i].average);
}
FILE *fp;
if((fp = fopen("stud","w"))== NULL)
{
printf("error:cannot open file!
");
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;
}