某次考试的成绩表如下,请用C语言编写程序对该成绩表进行处理。实现
1、按考号从低到高排序,结果显示列依次为“考号、姓名、学科一、学科二、学科三”
2、按总分(学科一、二、三成绩相加之和)从高到低排序,结果显示列依次为“考号、姓名、学科一、学科二、学科三”
所给txt文件大致如下图所示。
![](https://img-blog.csdnimg.cn/e78125adca8c4af2951524364ce9cdf2.png)
解题流程:
1、先把文件的第一行去掉,整理成如下图所示的样子。
![](https://img-blog.csdnimg.cn/7cabcdb67243458cbae46dbfdd4dddc3.png)
2、将文件中的数据读取
3、进行相应的排序
4、打印出来
代码如下:
#include <stdio.h>
#include <stdlib.h>
struct Stu //定义5个结构体数组来存放数据。具体定义几个,根据数据的量而定。
{
long Num;
char name[10];
int score_1;
int score_2;
int score_3;
}student[5];
int main()
{
struct Stu t; //定义一个中间变量
int i=0,j=0;
FILE *fp; // 定义文件指针
fp = fopen("data.txt", "r"); //只读,为输入打开一个文件。文件路径视自己情况而定。
if(fp==NULL) // 若fp是一个空指针,则表明data.txt不存在。输出提示信息。
{
printf("can't open the file");
exit(0);
}
for(i=0;i<5;i++)//循环读取数据
{
fscanf(fp,"%ld%s%d%d%d",&student[i].Num,student[i].name,&student[i].score_1,\
&student[i].score_2,&student[i].score_3);
}
for(i=0;i<4;i++)//冒泡排序
{
for(j=i+1;j<5;j++)
{
if(student[i].Num>student[j].Num)//满足一定条件就交换结构体数组的数据。
{
t = student[j];
student[j] = student[i];
student[i] = t;
}
}
}
for(i=0;i<5;i++)//打印将考号排序后的数据
{
printf("Num=%ld,name=%s,score_1=%d,score_2=%d,score_3=%d\n",\
student[i].Num,student[i].name,student[i].score_1,\
student[i].score_2,student[i].score_3);
}
//第二问
printf("第二问\n");
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
{
if((student[i].score_1+student[i].score_2+student[i].score_3)<\
(student[j].score_1+student[j].score_2+student[j].score_3))
{
t = student[j];
student[j] = student[i];
student[i] = t;
}
}
}
for(i=0;i<5;i++)
{
printf("Num=%ld,name=%s,score_1=%d,score_2=%d,score_3=%d\n",\
student[i].Num,student[i].name,student[i].score_1,\
student[i].score_2,student[i].score_3);
}
fclose(fp);
return 0;
}
运行结果:
![](https://img-blog.csdnimg.cn/b7e565444a0743dfafc7046c469a6bf7.png)
水平有限,欢迎指正。