主题:为什么排不了序
#include<stdio.h>
struct student
{
int num;
char name[10];
float score[3];
float total[5];
float ave[5];
}stu[5], temp;
void write()
{
int i;
for(i=0;i<5;i++)
{
scanf("%s%d%f%f%f",stu[i].name,&stu[i].num,&stu[i].score[0],&stu[i].score[1],&stu[i].score[2]);
stu[i].total[i]=stu[i].score[0]+stu[i].score[1]+stu[i].score[2];
stu[i].ave[i]=stu[i].total[i]/3;
}
FILE *fp;
if((fp=fopen("stu","wb"))==NULL)
{
printf("cannot open file\n");
return ;
}
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("stu","rb");
for(i=0;i<5;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
printf("%s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n",stu[i].name,stu[i].num,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].ave[i]);
}
fclose(fp);
}
void sort()
{
int j=0,i;FILE *fp;
if((fp=fopen("stu","wb"))==NULL)
{
printf("cannot open file\n");
return ;
}
for(i=0;i<5;i++)
if (fwrite(&stu[i],sizeof(struct student),1,fp)!=1);
printf("file write error\n");
fclose(fp);
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
if (stu[i].ave<stu[j].ave)
{
temp=stu[i];
stu[i]=stu[j];
stu[j]=temp;
}
}
printf("排序后的成绩是\n");
fp=fopen("stu","rb");
for(i=0;i<5;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
printf("%s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n",stu[i].name,stu[i].num,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].ave[i]);
}
fclose(fp);
}
void main()
{
printf("请输入五名学生的三门成绩\n");
write();
sort();
}
struct student
{
int num;
char name[10];
float score[3];
float total[5];
float ave[5];
}stu[5], temp;
void write()
{
int i;
for(i=0;i<5;i++)
{
scanf("%s%d%f%f%f",stu[i].name,&stu[i].num,&stu[i].score[0],&stu[i].score[1],&stu[i].score[2]);
stu[i].total[i]=stu[i].score[0]+stu[i].score[1]+stu[i].score[2];
stu[i].ave[i]=stu[i].total[i]/3;
}
FILE *fp;
if((fp=fopen("stu","wb"))==NULL)
{
printf("cannot open file\n");
return ;
}
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("stu","rb");
for(i=0;i<5;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
printf("%s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n",stu[i].name,stu[i].num,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].ave[i]);
}
fclose(fp);
}
void sort()
{
int j=0,i;FILE *fp;
if((fp=fopen("stu","wb"))==NULL)
{
printf("cannot open file\n");
return ;
}
for(i=0;i<5;i++)
if (fwrite(&stu[i],sizeof(struct student),1,fp)!=1);
printf("file write error\n");
fclose(fp);
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
if (stu[i].ave<stu[j].ave)
{
temp=stu[i];
stu[i]=stu[j];
stu[j]=temp;
}
}
printf("排序后的成绩是\n");
fp=fopen("stu","rb");
for(i=0;i<5;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
printf("%s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n",stu[i].name,stu[i].num,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].ave[i]);
}
fclose(fp);
}
void main()
{
printf("请输入五名学生的三门成绩\n");
write();
sort();
}