交换两个变量的值
程序员文章站
2022-07-03 19:18:43
...
方法一:使用中间变量
temp = m;
m = n;
n = temp;
int m = 12;
int n = 5;
int temp = m; //中间变量temp
m = n;
n = temp;
System.out.println("m:" + m + " n:" + n);
方法二:直接在输出的时候交换
int m 12;
int n 5;
System.outt.println("m:" + n + " n:" + m);
方法三:加减法
m = m + n; //m = 12 + 5;
n = m - n; //n = 17 - 5;
m = m - n; //m = 17- 12;
当m和n较大时,有可能出现精度损失
int m = 12;
int n = 5;
m = m + n;
n = m - n;
m = m - n;
System.out.println("m:" + m + " n:" + n);
方法四:乘除法
m = m * n; //m = 12 * 4
n = m / n; //n = 48 / 4
m = m / n; //m = 48 / 4
有可能出现精度损失
int m = 12;
int n = 4;
m = m * n;
n = m / n;
m = m / n;
System.out.println("m:" + m + " n:" + n);
方法五:异或法
m = m ^ n;
n = m ^ n; //(m ^ n) ^ n == m
m = m ^ n; //(m ^ n) ^ m == n
0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | (m=12) | |
^ | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | (n=5) |
0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | (m^n) |
0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | (m^n) | |
^ | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | (n=5) |
0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | (m ^ n) ^ n |
0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | (m ^ n) ^ n | |
^ | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | (n=5) |
0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | (m ^ n) ^ m |
int m = 12;
int n = 5;
m = m ^ n;
n = m ^ n; //(m ^ n) ^ n == m
m = m ^ n; //(m ^ n) ^ m == n
System.out.println("m:" + m + " n:" + n);
下一篇: C语言交换两个变量的值,用指针方式