#1391. 按平均分排序-课后习题10.6

按平均分排序-课后习题10.6

问题描述

将第5题stud文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存人一个新文件stu_sort中。

格式

输入

输入的格式

输出

输出的格式

样例

110      Li      90      89      88     89.00 
     120    Wang      80      79      78     79.00
     130    Chen      70      69      68     69.00 
     140      Ma     100      99      98     99.00 
     150     Wei      60      59      58     59.00
Now: 
140 Ma 100 99 98 99.00
110 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;
 }


提示

数据范围、额外说明、样例说明等等