c语言程序设计平均分排序,将第5题stud文件中的学生数据,按平均分进行排序处理...

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

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

解法1【c源程序】

#include

#include

#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

for (j=i+1;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

{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;

}

解法2【c源程序】

#include

#include

#define SIZE 5

struct student

{

char name[10];

int num;

int score[3];

float ave;

}  stud[SIZE],work;

int main()

{

void sort(void);

int i;

FILE *fp;

sort();

fp=fopen("stud_sort.dat","rb");

printf("sorted student's scores list as follow\n");

printf("----------------------------------------------------\n");

printf(" NAME      N0.     SCORE1   SCORE2   SCORE3    AVE    \n");

printf("----------------------------------------------------\n");

for (i=0;i

{

fread(&stud[i],sizeof(struct student),1,fp);

printf("%-10s %3d %8d %8d %8d %9.2f\n",stud[i].name,stud[i].num,

stud[i].score[0],stud[i].score[1],stud[i].score[2],stud[i].ave);

}

fclose(fp);

return 0;

}

void sort(void)

{FILE *fp1,*fp2;

int i,j;

if ((fp1=fopen("stu.dat","rb"))==NULL)

{printf("The file can not open\n\n");

exit(0);

}

if ((fp2=fopen("stud_sort.dat","wb"))==NULL)

{printf("The file write error\n");

exit(0);

}

for (i=0;i

if (fread(&stud[i],sizeof(struct student),1,fp1)!=1)

{printf("file read error\n");

exit(0);

}

for (i=0;i

{for (j=i+1;j

if (stud[i].ave

{work=stud[i];

stud[i]=stud[j];

stud[j]=work;

}

fwrite(&stud[i],sizeof(struct student),1,fp2);

}

fclose(fp1);

fclose(fp2);

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值