年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2492|回复: 2

交换两个数字的两种算法

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-2-20 21:38:07 | 显示全部楼层 |阅读模式
    如果有变量a=10, b=11,将a、b两变量的值进行交换,如何操作?
    1、使用第三个变量temp
    1. #include <stdio.h>
    2. int main() {
    3.    
    4.                 int a = 10;
    5.                 int b = 11;
    6.                 printf("Before switch:\n a=%d, b=%d\n", a, b);
    7.                 int temp;
    8.                 temp = a;
    9.                 a = b;
    10.                 b = temp;
    11.                 printf("After switch:\n a=%d, b=%d\n",a ,b);
    12.    
    13. }
    复制代码
    2、通过运算相互交换
    1. #include <stdio.h>
    2. int main() {
    3.    
    4.                 int a = 10;
    5.                 int b = 11;
    6.    
    7.                 printf("Before switch:\n a=%d, b=%d\n", a, b);
    8.    
    9.                 a = a + b;
    10.                 b = a - b;
    11.                 a = a - b;
    12.    
    13.                 printf("After switch:\n a=%d, b=%d\n",a ,b);
    14.    
    15. }
    复制代码
    PS:第二种方法需要一定的空间想像能力!!
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

     楼主| 发表于 2014-2-20 21:40:37 | 显示全部楼层
    输出结果为:
    1. Before switch:
    2. a=10, b=11
    3. After switch:
    4. a=11, b=10
    复制代码
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

     楼主| 发表于 2014-3-2 12:08:38 | 显示全部楼层
    还有第三个方法:
    1. #include <stdio.h>
    2. int main() {
    3.     int a = 10;
    4.     int b = 11;
    5.    
    6.     // 利异或的规律a^b^b == a
    7.     a = a ^ b;
    8.     b = a ^ b;
    9.     a = a ^ b;
    10.    
    11.     printf("a=%d, b=%d\n", a, b);
    12. }
    复制代码

    同样可以得出互换的效果
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-4-27 14:33 , Processed in 0.050191 second(s), 19 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表