您的位置:首页 > 编程语言 > C语言/C++

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

2011-08-22 17:11 357 查看
关于交换数据,第一个想到的是利用中间变量。

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

相信想到加法的人有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*/ 
}


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

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



粗细。。???是吗?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐