有5个学生的信息,现在要求按照成绩高低排名,运行结果好像都是0~~
#include<stdio.h>
struct student
{
int num;
char name[20];
int score;
}stu[5]={{1001,"li",99},{1002,"xin",101},{1003,"tian",103},{1004,"he",130},{1005,"shu",130}};
int main()
{ struct student temp;
const int n=5;
int i,j,k;
printf("由低到高的顺序是:\n");
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
if(stu[j].score>stu[k].score)
k=j;
temp=stu[k];
stu[k]=stu[i];
stu[i]=temp;
}
for(i=0;i<n;i++)
{
printf("%6d %8s %6.2f\n",stu[i].num,stu[i].name,stu[i].score);
printf("\n");
}
return 0;
}
举个例子吧
#include<stdio.h>
struct Student
{
int num;
char name[20];
float score;
}temp;
void main()
{
int stuNum;
struct Student stu[50];
printf("请确定录入学生人数:");
scanf("%d",&stuNum);
printf("请输入学生信息(学号,姓名,分数):\n");
int i,j,k;
for(i=0;i<stuNum;i++){
scanf("%d %s %f",&stu[i].num,&stu[i].name,&stu[i].score);
}
//按成绩高低输出--简单的冒泡排序
for(j=1;j<stuNum;j++){
for(k=0;k<stuNum-j;k++){
if(stu[k].score>stu[k+1].score){
temp=stu[k+1];
stu[k+1]=stu[k];
stu[k]=temp;
}
}
}
printf("成绩排名如下:\n");
//输出排序结果
for(i=0;i<stuNum;i++){
printf("%d\t%s\t%f\n",stu[i].num,stu[i].name,stu[i].score);
}
}
如果对你有帮助,请采纳谢谢
score是整型,你用%6.2f输出是错的,应该用%d。%f是用来输出浮点数的
排序里这么改下:
for (i = 0; i < n - 1; i++)
{
k = i;
for (j = i + 1; j < n; j++)
if (stu[j].score > stu[k].score)
k = j;
if (k != i)
{
temp = stu[k];
stu[k] = stu[i];
stu[i] = temp;
}
}