注册 登录
编程论坛 C语言论坛

排序算法没起作用就好像这个算法不存在一样

domore 发布于 2019-08-06 05:15, 2151 次点击
只有本站会员才能查看附件,请 登录


#include<stdio.h>
struct Student
    {
    int num;    //学号
    char name[20];    //名字
    float score;     //分数
    };


int main()
    {
    struct Student stu[5]=
            {
            {10010,"Li",80},
            {10015,"Po",90},
            {10020,"Wu",76},
            {10034,"Qi",79},
            {10056,"Zhang",89}
            };
    struct Student temp;    //交换用到的结构体变量temp
    const int n=5;
    int i,j;
    printf("the order is:\n");
    for(i=0;i<n-1;i++)      //按分数高低排序
        for(j=i+1;j<n;j++)
            if(stu[j].score>stu[i].score)
           //temp=stu[i];stu[i]=stu[j];stu[j]=temp;
           temp=stu[j];stu[j]=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);
    return 0;
    }
6 回复
#2
wmf20142019-08-06 08:57
把数据交换的前两个分号改成逗号试试,即“temp=stu[j],stu[j]=stu[i],stu[i]=temp;”
#3
TysonKoothra2019-08-06 09:07
temp=stu[j];stu[j]=stu[i];stu[i]=temp;用大括号包围起来。
#4
zhulei19782019-08-06 19:50
结构不能这样赋值吧,要分开来赋值吧
 temp.num=stu[j].num;
 strcpy(temp.name,stu[j].name);
 temp.score=stu[j].score;

像这样
#5
TysonKoothra2019-08-06 19:57
回复 4楼 zhulei1978
结构体可以直接赋值。
#6
八画小子2019-08-06 20:53
以下是引用zhulei1978在2019-8-6 19:50:53的发言:

结构不能这样赋值吧,要分开来赋值吧
 temp.num=stu[j].num;
 strcpy(temp.name,stu[j].name);
 temp.score=stu[j].score;
 
像这样
结构体的赋值,在底层实现为内存区域的复制,所以可以直接赋值。
#7
zbjzbj2019-08-06 22:41
A: if(stu[j].score>stu[i].score)
           {temp=stu[j];} stu[j]=stu[i];stu[i]=temp;

B:if(stu[j].score>stu[i].score)
           {temp=stu[j];stu[j]=stu[i];stu[i]=temp;}


楼主,你认为A,B两段代码等效吗?我再答非所问一次。

[此贴子已经被作者于2019-8-6 22:43编辑过]

1