#1392. 插入成绩排序-课后习题10.7
插入成绩排序-课后习题10.7
问题描述
将第6题已排序的学生成绩文件进行插入处理。插入一个学生的3门课程成绩,程序先计算新插入学生的平均成绩,然后将它按成绩高低顺序插入,插人后建立一个新文件。
样例
NO.:160 name:Tan
score1,score2,score3:98,97.98
original data:
140 Ma 100 99 98 99.00
101 Li 90 89 88 89.00
120 Wang 80 79 78 68 79.00
130 Chen 70 69 68 69.00
150 Wei 60 59 58 59.00
Now:
140 Ma 100 99 98 99.00
160 Tan 98 97 98 97.67
101 Li 90 89 88 89.00
120 Wang 80 79 78 79.00
130 Chen 70 69 68 69.00
150 Wei 60 59 58 59.00
题解
#include <stdio.h>
#include <stdlib.h>
#define N 10
struct student
{char num[10];
char name[8];
int score[3];
float ave;
}st[N],temp;
int main()
{FILE *fp;
int i,j,n;
//读文件
if ((fp=fopen("stud","r"))==NULL)
{printf("can not open.\n");
exit(0);
}
printf("File 'stud': ");
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);
}
printf("\n");
fclose(fp);
n=i;
//排序
for (i=0;i<n;i++)
for (j=i+1;j<n;j++)
if (st[i].ave < st[j].ave)
{temp=st[i];
st[i]=st[j];
st[j]=temp;
}
//输出
printf("\nNow:");
fp=fopen("stu_sort","w");
for (i=0;i<n;i++)
{fwrite(&st[i],sizeof(struct student),1,fp);
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);
return 0;
}
提示
数据范围、额外说明、样例说明等等