交换两个数字,不借助于第三个变量的三种简单的方法。
1 #include <stdio.h>
2 int main()
3 {
4 int a = 10,b=20;
5 // solution 1: a = a+b; b = a-b; a = a-b;
6 printf("*********************************************\n");
7 printf("Change two number without another number!!!!\n");
8 printf("*********************************************\n");
9 printf("Solution 1:\n");
10 printf("a:%d b:%d\n",a,b);
11 a = a + b;
12 b = a - b;
13 a = a - b;
14 printf("a:%d b:%d\n",a,b);
15 printf("*********************************************\n");
16 printf("Solution 2:\n");
17 // solution 2:
18 a = 10;
19 b = 20;
20 printf("a:%d b:%d\n",a,b);
21 a = a*b;
22 b = a/b;
23 a = a/b;
24 printf("a:%d b:%d\n",a,b);
25
26 printf("*********************************************\n");
27 printf("Solution 3:\n");
28 // solution 3:a^=b^=a^=b;
29 a = 10;
30 b = 20;
31 printf("a:%d b:%d\n",a,b);
32 a = a^b;//put the information into a
33 b = a^b;//make b equal to the orginal a
34 a = a^b;//make a equal to the orginal b
35 printf("c:%d d:%d\n",a,b);
36
37 return 0;
38 }
以上为三种交换两个整数数字不借助于第三个变量的方法。。其中最好的为第一种方法,因为针对后两种方法。如果交换的不是整数,那么就会出现差错。
posted on 2012-03-23 16:18 NewPanderKing 阅读(1620) 评论(1) 编辑 收藏 举报