c程序设计第四版谭浩强
将第7题结果仍存入原有的”stu_sort"文件而不另建新文件。
第7题内容:将第6题已排序的学生成绩文件进入插入处理。插入一个学生的3门课程成绩,程序先计算新插入学生的平均成绩,然后将它按成绩高低顺序插入,插入后建立一个新文件。
第6题内容:将第5题“stud”文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存入一个新文件“stu_sort“中。
第5题内容:有5个学生,每个学生有3门课程的成绩,从键盘输入学生数据(包括学号、姓名、三门课的成绩),计算出平均成绩,将原有数据和计算出平均分数存放在磁盘文件“stud”中 。
c程序设计(第四版)学习辅导 谭浩强 编著
【c源程序】
#include <stdio.h>
#include <stdlib.h>
struct student
{char num[10];
char name[8];
int score[3];
float ave;
} st[10],s;
int main()
{FILE *fp,*fp1;
int i,j,t,n;
printf("\nNO.:");
scanf("%s",s.num);
printf("name:");
scanf("%s",s.name);
printf("score1,score2,score3:");
scanf("%d,%d,%d",&s.score[0],&s.score[1],&s.score[2]);
s.ave=(s.score[0]+s.score[1]+s.score[2])/3.0;
/*从文件读数据*/
if((fp=fopen("stu_sort","r"))==NULL)
{printf("can not open file.");
exit(0);
}
printf("original data:\n");
for (i=0;fread(&st[i],sizeof(struct student),1,fp)!=0;i++)
{printf("\n%8s%8s",st[i].num,st[i].name);
for (j=0;j<3;j++)
printf("%8d",st[i].score[j]);
printf("%10.2f",st[i].ave);
}
n=i;
for (t=0;st[t].ave>s.ave && t<n;t++);
/*向文件写数据*/
printf("\nNow:\n");
fp1=fopen("sort1.dat","w");
for (i=0;i<t;i++)
{fwrite(&st[i],sizeof(struct student),1,fp1);
printf("\n %8s%8s",st[i].num,st[i].name);
for (j=0;j<3;j++)
printf("%8d",st[i].score[j]);
printf("%10.2f",st[i].ave);
}
fwrite(&s,sizeof(struct student),1,fp1);
printf("\n %8s %7s %7d %7d %7d%10.2f",s.num,s.name,s.score[0],
s.score[1],s.score[2],s.ave);
for (i=t;i<n;i++)
{fwrite(&st[i],sizeof(struct student),1,fp1);
printf("\n %8s%8s",st[i].num,st[i].name);
for(j=0;j<3;j++)
printf("%8d",st[i].score[j]);
printf("%10.2f",st[i].ave);
}
printf("\n");
fclose(fp);
fclose(fp1);
return 0;
}
本文链接:http://www.wb98.com/c/post/tanhaoqiang_10.8.html
本站文章搜索: