Learn more11111 2022-02-25 18:13 采纳率: 33.3%
浏览 15
已结题

交换值时有中间变量和没有中间变量的区别是什么

int i,j;
printf("The order is\n");//为什么加一个中间变量k就能输出结果

for(i=0;i<N-1;i++)
{ 
    for(j=i+1;j<N;j++)
        if(stu[j].score>stu[i].score)
        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);
    }
    printf("\n");        

return 0;
}

  • 写回答

1条回答 默认 最新

  • _GX_ 2022-02-25 18:36
    关注

    如果不用中间变量交换,你可以考虑用XOR Swap

    #include <stdio.h>
    
    /** Inplace swap using the XOR operation */
    void xor_swap(int *a, int *b)
    {
        if (a != b)
        {
            *a ^= *b; // a = A XOR B
            *b ^= *a; // b = B XOR ( A XOR B ) = A
            *a ^= *b; // a = ( A XOR B ) XOR A = B
        }
    }
    
    void xor_swapf(float *a, float *b)
    {
        xor_swap((int *)a, (int *)b);
    }
    
    int main()
    {
        int a = 1, b = 2;
        float c = 1.23, d = 4.56;
        printf("before:\n");
        printf("a=%d b=%d\n", a, b);
        printf("c=%f d=%f\n", c, d);
        xor_swap(&a, &b);
        xor_swapf(&c, &d);
        printf("after:\n");
        printf("a=%d b=%d\n", a, b);
        printf("c=%f d=%f\n", c, d);
        return 0;
    }
    
    $ gcc -Wall main.c
    $ ./a.out
    before:
    a=1 b=2
    c=1.230000 d=4.560000
    after:
    a=2 b=1
    c=4.560000 d=1.230000
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月6日
  • 已采纳回答 2月26日
  • 创建了问题 2月25日

悬赏问题

  • ¥15 学习Python如何找兼职
  • ¥15 python结合Matlab仿真忆阻器
  • ¥35 有人会注册whatsaop协议号吗?
  • ¥15 lead dbs 无法导入影像数据
  • ¥15 多目标MPA算法优化编程实现
  • ¥15 反激PWM控制芯片调研
  • ¥15 Python for loop减少运行时间
  • ¥15 fluent模拟物质浓度udf
  • ¥15 Collection contains no element matching the predicate
  • ¥20 冻品电商平台的搜索是怎么实现的