#include<stdio.h>
#include<ctype.h>
#include<fstream>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef struct student{
int id;
char name[20];
float grade;
struct student *next;
}Student;
Student *head=NULL;
void read();
void Sort();
void write();
int main(){
head=(Student *)malloc(sizeof(Student));
read();
Sort();
write();
return 0;
}
void read(){
FILE *fp;
fp=fopen("c:\\grad.txt","r");
Student *temp;
if(fp!=NULL){
int ID;
while(fscanf(fp,"%d ",&ID)!=EOF){
temp=(Student *)malloc(sizeof(Student));
head->id=ID;
fscanf(fp,"%s %f\n",head->name,&head->grade);
temp->next=head;
head=temp;
}
fclose(fp);
printf("写入成功\n");
}
else printf("open error\n");
return ;
}
void Sort(){
Student *p,*r,*t,*end,*temp;
end=NULL;
while(head->next!=end){
p=head;
r=p->next;
t=r->next;
for(;t!=end;p=p->next,r=r->next,t=t->next){
if(r->grade<t->grade){
r->next=t->next;
t->next=r;
p->next=t;
temp=t;
t=r;
r=temp;
}
}
end=r;
}
return ;
}
void write(){
FILE *fp;
fp=fopen("rank.txt","w");
double average=0;
int n=0;
Student *s,*r;
s=head->next;
while(s!=NULL){
n++;
average+=s->grade;
s=s->next;
}
char ss[20]="Totalnumber";
fprintf(fp,"%s:%.2f\n",ss,average);
char aa[20]="average grade";
average/=n;
fprintf(fp,"%s:%.2f\n",aa,average);
s=head->next;
while(s!=NULL){
fprintf(fp,"%d %s %f\n",s->id,s->name,s->grade);
s=s->next;
}
fclose(fp);
s=head;
r=head->next;
while(r!=NULL){
free(s);
s=r;
r=r->next;
}
free(s);
return ;
}