C语言中交换数据——这个您想不到,其实可以想到的

 关于交换数据,第一个想到的是利用中间变量。

再想想还能想到的是 加法吧,如果再想想的话可能又会有地址之类的,但是您想过没有

相信想到加法的人有50%

能想到加法会溢出的人只有 1%吧。。。

我真的没有想到,能看到真的是幸运的了,哈哈

/************************************************************************/ 
/* purpose:learn how to swith number with most efficient                */ 
/* contact:guozhengqian0825@126.com                                        */ 
/* data      :2011.08.22                                                    */ 
/* author:qianguozheng (钱国正)                                            */ 
/************************************************************************/ 
 
#include "stdio.h" 
 
void main() 
{ 
    int a=10; 
    int b=20; 
    printf("before switch: a=%d,b=%d\n",a,b); 
    /*method one : is the best one!*/ 
 
    a=a^b;//a=00001010 
    b=a^b;//b=00010100 
    a=a^b; 
    printf("after switch: a=%d,b=%d\n",a,b); 
    /* 
        a=00001010 
        b=00010100 
    a=a^b=00011110 
        b=00010100 
    b=a^b=00001010=10 
        a=00011110 
    a=a^b=00010100=20 
 
    */ 
 
    /*method two */ 
    /*compare to method one ,the shortback is that : 
        when a is the max of the type and  
             b is the max of the typw two  
             it will full overflow(溢出) 
    */ 
    a=a+b; 
    b=a-b; 
    b=a-b; 
    printf("after switch: a=%d,b=%d\n",a,b); 
 
    /*method three*/ 
 
    int tmp; 
    tmp =a ; 
    a=b; 
    b=tmp; 
 
    /*this is the normal ,anyone who is called programme can do that*/ 
 
    /*i will not show others to you ,just remember the first one is enough*/ 
}



 这个例子最简单不过了,但是折射的道理却非常的重要,我们往往在想过一个问题的解决方案之后,就高兴的过头了,忘记了对这个方案的优化,

哪怕是略微的想想,其实这些发现都很简单,却经常笨人所忽略。。。。。

 

粗细。。???是吗?

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钱国正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值