题目描述:给定一个存有学生成绩的文本文档grad.txt,要求写一个C程序统计其总人数和平均分,并按成绩进行降序排序,将总人数、平均分、降序结果输出到rank.txt 中。
![](https://img-blog.csdnimg.cn/20190909144748151.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyODE1MTg4,size_16,color_FFFFFF,t_70)
结构体+文件操作+链表降序
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<windows.h>
typedef struct node //学生信息
{
int id; //学号
char name[20]; //姓名
double grade; //分数
struct node *next;
}node;
//从文件中读取数据存入链表
node *createlink()
{
node *head,*pre,*p; //pre保存当前结点的前驱结点,head为头结点
head = (node *)malloc(sizeof(node)); //创建头结点
pre = head; //记录pre为head
int a;
char b[20];
double c;
FILE *r = fopen("grad.txt","r");
if(r==NULL)
{
printf("打开文件失败!");
return NULL;
}
while(fscanf(r,"%d%s%lf",&a,&b,&c)!=EOF)
{
p = (node *)malloc(sizeof(node)); //新建结点
p->id = a; //保存数据域
strcpy(p->name,b);
p->grade = c;
pre->next = p; //前驱结点的指针域设为当前新建结点的地址
pre = p; //把pre设为p,作为下个结点的前驱结点
}
pre->next = NULL;
return head;
}
//按照成绩降序排序
void Sort(node *head)
{
node *m = head;
if(head->next==NULL || head->next->next==NULL)
{
printf("链表排序完成!\n");
return;
}
node *p = head->next;
node *s = p->next;
node *k = NULL;
while(k != head->next->next)
{
while(s!=k)
{
if(p->grade < s->grade)
{
p->next = s->next;
s->next = p;
m->next = s;
m = s;
s = p->next;
}
else
{
m = p;
p = s;
s = s->next;
}
}
k = p;
m = head;
p = m->next;
s = p->next;
}
printf("链表排序完成!\n");
}
//统计总人数 和 平均分
void get(node *head)
{
double sum = 0;
int cnt = 0;
node *p;
p = head->next; //指向第一个有效结点
FILE *w = fopen("rank.txt","w");
if(w==NULL)
{
printf("打开文件失败!");
return;
}
while(p)
{
sum += p->grade;
cnt++;
p = p->next;
}
//输出链表节点数据到屏幕
printf("%d %f\n",cnt,sum/cnt);
//输出链表节点数据到文件output.txt
fprintf(w,"%d %f\n",cnt,sum/cnt);
fclose(w);
return;
}
//输出链表到屏幕和文件output.txt
void show(node *head)
{
node *p;
p = head->next; //指向第一个有效结点
FILE *w = fopen("rank.txt","a+");
if(w==NULL)
{
printf("打开文件失败!");
return;
}
while(p)
{
//输出链表节点数据到屏幕
printf("%d %s %f\n",p->id,p->name,p->grade);
//输出链表节点数据到文件output.txt
fprintf(w,"%d %s %f\n",p->id,p->name,p->grade);
p = p->next;
}
fclose(w);
return;
}
int main()
{
node *head;
head = createlink();
get(head);
Sort(head);
show(head);
return 0;
}
结果如图所示: