将第6题已排序的学生成绩文件进入插入处理。插入一个学生的3门课程成绩

2016-06-20 11:50:03  分类: c程序设计第四版谭浩强课后答案  参与:

  将第6题已排序的学生成绩文件进入插入处理。插入一个学生的3门课程成绩,程序先计算新插入学生的平均成绩,然后将它按成绩高低顺序插入,插入后建立一个新文件。

第6题内容:将第5题“stud”文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存入一个新文件“stu_sort“中。

第5题内容:有5个学生,每个学生有3门课程的成绩,从键盘输入学生数据(包括学号、姓名、三门课的成绩),计算出平均成绩,将原有数据和计算出平均分数存放在磁盘文件“stud”中 。

【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;
 }

来源:c程序设计第四版谭浩强课后答案

本文链接:http://www.wb98.com/c/post/tanhaoqiang_10.7.html

本站文章搜索:

<< 上一篇下一篇 >>

搜索

网站分类

Tags列表

赞助商链接