请教C语言
在函数中进行 10个学生成绩从高到低排名 , 再改进函数, 进行 n个学生成绩从高到低排名, 排名方式根据函数的style参数进行,如style为‘a'按升序排,style为 ' d ' 按降序排。
( a:ascending 升,d:descending 降) 展开
附:程序运行图片
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student{
float score;
char name[10];
struct student *next;
};
int n;
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
n=0;
head=(struct student *)malloc(LEN);
p1=p2=(struct student *)malloc(LEN);
printf("please enter the name and the score of the student, separet by pause\n");
scanf("%s%f",&p1->name,&p1->score);
head->next=NULL;
while((p1->score)!=0)
{
n=n+1;
if(n==1) head->next=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%s%f",&p1->name,&p1->score);
}
p2->next=NULL;
return (head);
}
void ascending(struct student *head)
{
int i,j;
struct student *p,*p1,*p2;
for(i=0;i<n-1;i++)
{ p=head;
p1=p2=head->next;
for(j=0;j<n-1;j++)
{ p2=p1=p->next;
p1=p2->next;
if(p1->score<p2->score)
{ p->next=p1;
p2->next=p1->next;
p1->next=p2;
}
p=p->next;
}
}
}
void decending(struct student *head)
{
int i,j;
struct student *p,*p1,*p2;
for(i=0;i<n-1;i++)
{ p=head;
p1=p2=head->next;
for(j=0;j<n-1;j++)
{ p2=p1=p->next;
p1=p2->next;
if(p1->score>p2->score)
{ p->next=p1;
p2->next=p1->next;
p1->next=p2;
}
p=p->next;
}
}
}
void sort(struct student *head,char c)
{
if(c=='a'||c=='A')
ascending(head);
else
decending(head);
}
void print(struct student *head)
{
while(head->next!=NULL)
{
head=head->next;
printf("%12s,%8.2f",head->name,head->score);
printf("\n");
}
}
int main()
{
struct student *head;
char c;
head=creat();
printf("which style you want to show: ascending or descending?\n");
getchar();
do{
printf("now enter your choice: a or d ?\n");
scanf("%c",&c);
}while(c!='a'&&c!='A'&&c!='d'&&c!='D');
sort(head,c);
printf("here are the messege of the students:\n");
printf("\tname,\tscore\n\n");
print(head);
return 0;
}
mail:hex_china@qq.com