有5个学生,每个学生有3门课程的成绩,从键盘输入学生数据(包括学号、姓名、三门课的成绩),计算出平均成绩,将原有数据和计算出平均分数存放在磁盘文件“stud”中 。
解法1【c源程序】
#include
struct student
{char num[10];
char name[8];
int score[3];
float ave;
} stu[5];
int main()
{ int i,j,sum;
FILE *fp;
for(i=0;i<5;i++)
{printf("\ninput score of student %d:\n",i+1);
printf("NO.:");
scanf("%s",stu[i].num);
printf("name:");
scanf("%s",stu[i].name);
sum=0;
for (j=0;j<3;j++)
{printf("score %d:",j+1);
scanf("%d",&stu[i].score[j]);
sum+=stu[i].score[j];
}
stu[i].ave=sum/3.0;
}
/*将数据写入文件*/
fp=fopen("stud","w");
for (i=0;i<5;i++)
if (fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
printf("file write error\n");
fclose(fp);
fp=fopen("stud","r");
for (i=0;i<5;i++)
{fread(&stu[i],sizeof(struct student),1,fp);
printf("\n%s,%s,%d,%d,%d,%6.2f\n",stu[i].num,stu[i].name,stu[i].score[0],
stu[i].score[1],stu[i].score[2],stu[i].ave);}
return 0;
}
解法2【c源程序】
#include
#define SIZE 5
struct student
{char name[10];
int num;
int score[3];
float ave;
} stud[SIZE];
int main()
{ void save(void);
int i;
float sum[SIZE];
FILE *fp1;
for (i=0;i
{ scanf("%s %d %d %d %d",stud[i].name,&stud[i].num,&stud[i].score[0],
&stud[i].score[1],&stud[i].score[2]);
sum[i]=stud[i].score[0]+stud[i].score[1]+stud[i].score[2];
stud[i].ave=sum[i]/3;
}
save();
fp1=fopen("stu.dat","rb");
printf("\n name NO. score1 score2 score3 ave\n");
printf("-----------------------------------------------\n");
for (i=0;i
{fread(&stud[i],sizeof(struct student),1,fp1);
printf("%-10s %3d %7d %7d %7d %8.2f\n",stud[i].name,stud[i].num,
stud[i].score[0],stud[i].score[1],stud[i].score[2],stud[i].ave);
}
fclose (fp1);
return 0;
}
void save(void)
{
FILE *fp;
int i;
if ((fp=fopen("stu.dat","wb"))==NULL)
{printf("The file can not open\n");
return;
}
for(i=0;i
if (fwrite(&stud[i],sizeof(struct student),1,fp)!=1)
{printf("file write error\n");
return;
}
fclose(fp);
}