这个可能网上一搜一大把一大把的,可是今天我看到了一个新的写法,所以就写这篇文章记录一下,不不知道百度有没有,没去搜索!
方法1:这是最简单,也是最常用的一个方法!
int n1 = 10, n2 = 20; int tmp = n1; n1 = n2; n2 = tmp; Console.WriteLine("n1={0},n2={1}", n1, n2); Console.ReadKey();
方法2:算术运算
//交换两个变量,不使用第三个变量 int n1 = 10, n2 = 20; n1 = n1 + n2; n2 = n1 - n2; n1 = n1 - n2; Console.WriteLine("n1={0},n2={1}", n1, n2); Console.ReadKey();
方法3:这个是我今天要记录的重点
int n1 = 10, n2 = 20; n2 = n1 + (n1 = n2) * 0; Console.WriteLine("n1={0},n2={1}", n1, n2); Console.ReadKey();
方法4:多写点,面试的时候,逼格又上涨了一节!
//位运算 int n1 = 10, n2 = 20; n1 = n1 ^ n2; n2 = n1 ^ n2; n1 = n1 ^ n2; Console.WriteLine("n1={0},n2={1}", n1, n2); Console.ReadKey();
扩展:交换两个变量,封装成方法
//这样直接交换的话,你会发现输出的值并没有变! int n1 = 10, n2 = 20; Swap( n1, n2); Console.WriteLine("n1={0},n2={1}", n1, n2); Console.ReadKey(); private static void Swap( int n1, int n2) { int tmp = n1; n1 = n2; n2 = tmp; } //----------------------------------------------------------------------------------------- //把变量前边加上“ref” 把值类型变为引用类型(不明白可以百度这两个类型的区别) int n1 = 10, n2 = 20; Swap(ref n1, ref n2); Console.WriteLine("n1={0},n2={1}", n1, n2); Console.ReadKey(); private static void Swap(ref int n1, ref int n2) { int tmp = n1; n1 = n2; n2 = tmp; }
时间: 2024-12-29 01:44:53