今天在我们学校的OJ上做题,一道非常简单的题,突然想试试能不能不借助第三个变量,交换两个变量值。蒙出来一半了已经,好可惜。现在把方法写在这里,希望以后不要忘记。
1 void fun1() 2 { 3 int a = 10, b = 100; 4 5 a = a + b; 6 b = a - b; 7 a = a - b; 8 printf("%d\n%d\n", a, b); 9 } 10 11 void fun2() 12 { 13 int a = 10, b = 100; 14 a = a * b; 15 b = a / b; 16 a = a / b; 17 printf("%d\n%d\n", a, b); 18 } 19 20 void fun3() 21 { 22 int a = 10, b=100; 23 a ^= b;//^异或相同为0,相异为1. 24 b ^= a; 25 a ^= b; 26 printf("%d\n%d\n", a, b); 27 }
感谢网友 https://blog.csdn.net/sinat_29173167/article/details/52904252 的思路。
原文:https://www.cnblogs.com/lizhe-Ning/p/9158475.html