方法一:借助第三方变量
1 #region 1 利用第三方变量 2 int a = 10; 3 int b = 20; 4 Console.WriteLine("交换前的值:a={0},b={1}", a, b); 5 Console.ReadKey(); 6 int temp = a; 7 a = b; 8 b = temp; 9 Console.WriteLine("交换后的值:a={0},b={1}", a, b); 10 Console.ReadKey(); 11 #endregion
方法二:不借助第三方变量
1)加减法
1 #region 2 不利用三方变量 (加减法) 2 int a = 10; 3 int b = 20; 4 Console.WriteLine("交换前的值:a={0},b={1}", a, b); 5 Console.ReadKey(); 6 a = a + b; //30 7 b = a - b; //10 8 a = a - b; //20 9 Console.WriteLine("交换后的值:a={0},b={1}", a, b); 10 Console.ReadKey(); 11 #endregion
2)异或运算
1 /* 2 *分析:数字变为二进制在进行异或运算[0^1 = 1 ,0^0=0 1^1=0] 3 *10 ==> 01001 ==>a 4 *20 ==> 10100 ==>b 5 * a^b 6 * 01001 7 * 10100 8 * 11101 ==> a 9 * 10100 10 * 01001 ==>b(10) 11 * 11101 12 * 10100 ==>a(20) 13 */ 14 int a = 10; 15 int b = 20; 16 Console.WriteLine("交换前:a={0},b={1}", a, b); 17 Console.ReadKey(); 18 a = a ^ b; 19 b = a ^ b; 20 a = a ^ b; 21 Console.WriteLine("交换后:a={0},b={1}", a, b); 22 Console.ReadKey();