/* 8.8从文件ex88_1.txt中取出成绩,排序后,按降序存放EX88_2.TXT中 */
#include "stdio.h"
#define N 10
struct student
{
int num;
char name[20];
int score[3]; /*不能使用float*/
float average;
};
void sort(struct student stu[]);
void print(FILE *fp, struct student stu[]);
void printtopfive(FILE *fp, struct student stu[]);
void main()
{
struct student s[N];
int i;
FILE *fp1,*fp2;
char ch;
if((fp1=fopen("c:\\ex88_1.txt","r"))==NULL)
{
printf("不能打开文件c:\\ex88_1.txt");
exit(1);
}
if((fp2=fopen("c:\\ex88_2.txt","w"))==NULL)
{
printf("不能打开文件c:\\ex88_2.txt");
exit(1);
}
for(i=0;i<N;i++)
{
fscanf(fp1,"%d%s%d%d%d",&s[i].num,s[i].name,&s[i].score[0],
&s[i].score[1],&s[i].score[2]);
s[i].average=(s[i].score[0]+s[i].score[1]+s[i].score[2])/3.0;
}
fprintf(fp2,"原始成绩报表\n");
print(fp2,s);
sort(s);
fprintf(fp2,"排序之后的成绩报表\n");
print(fp2,s);
fprintf(fp2,"前五名成绩报表\n");
printtopfive(fp2,s);
}
void sort(struct student stu[])
{
int i,k,j;
struct student t;
for(i=0;i<N-1;i++)
{
k=i;
for(j=i+1;j<N;j++)
{
if(stu[k].average<stu[j].average)
k=j;
if(k!=i)
{
t=stu[i];
stu[i]=stu[k];
stu[k]=t;
}
}
}
}
void print(FILE *fp, struct student stu[])
{
int i;
fprintf(fp,"StudentID StudentName Score1 Score2 Score3 Average\n");
for(i=0;i<N;i++)
fprintf(fp,"%-10d%-12s%8d%8d%8d%8.1f\n",stu[i].num,stu[i].name,
stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].average);
}
void printtopfive(FILE *fp, struct student stu[])
{
int i;
fprintf(fp,"StudentName Average\n");
for(i=0;i<5;i++)
fprintf(fp,"%-12s%8.1f\n",stu[i].name,stu[i].average);
}
/*ex88_1.txt中取出成绩?
20001 姓名(1) 70 80 90
20002 姓名(2) 71 81 91
20003 姓名(3) 72 82 92
20004 姓名(4) 73 83 93
20005 姓名(5) 74 84 94
20006 姓名(6) 75 85 95
20007 姓名(7) 76 86 96
20008 姓名(8) 77 87 97
20009 姓名(9) 78 88 98
20010 姓名(10) 79 89 99
*/
/*排序后,按降序存放EX88_2.TXT中
原始成绩报表
StudentID StudentName Score1 Score2 Score3 Average
20001 姓名(1) 70 80 90 80.0
20002 姓名(2) 71 81 91 81.0
20003 姓名(3) 72 82 92 82.0
20004 姓名(4) 73 83 93 83.0
20005 姓名(5) 74 84 94 84.0
20006 姓名(6) 75 85 95 85.0
20007 姓名(7) 76 86 96 86.0
20008 姓名(8) 77 87 97 87.0
20009 姓名(9) 78 88 98 88.0
20010 姓名(10) 79 89 99 89.0
排序之后的成绩报表
StudentID StudentName Score1 Score2 Score3 Average
20010 姓名(10) 79 89 99 89.0
20009 姓名(9) 78 88 98 88.0
20008 姓名(8) 77 87 97 87.0
20007 姓名(7) 76 86 96 86.0
20006 姓名(6) 75 85 95 85.0
20005 姓名(5) 74 84 94 84.0
*/
标签:练习题,struct,int,void,ex88,C语言,student,txt,参考答案
From: https://blog.51cto.com/emanlee/8246700