编写程序交换两个数字而不使用第三个变量?

方法1((使用算术运算符):

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include <stdio.h>

 

int main()

{

  int a = 10, b = 5;

  // algo to swap 'a' and 'b'

  a = a + b;  // a becomes 15

  b = a - b;  // b becomes 10

  a = a - b;  // fonally a becomes 5

  printf("After Swapping the value of: a = %d, b = %d\n\n", a, b);

  return 0;

}

 

方法2(使用按位异或运算符):

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include <stdio.h>

 

int main()

{

  int a = 10, b = 5;

  // algo to swap 'a' and 'b'

  a = a ^ b;  // a becomes (a ^ b)

  b = a ^ b;  // b = (a ^ b ^ b), b becomes a

  a = a ^ b;  // a = (a ^ b ^ a), a becomes b

  printf("After Swapping the value of: a = %d, b = %d\n\n", a, b);

  return 0;

}

posted @ 2019-09-03 14:41  wdliming  阅读(258)  评论(0编辑  收藏  举报