提供一个临时变量
public class swapInt { public static void main(String[] agrs){ int m = 12; int n = 5; System.out.PRintln("m:"+m+" n:"+n); int temp = m; m = n; n = temp; System.out.println("m:"+m+" n:"+n);}缺点:当m和n较大时,有可能会出现精度损失
public class swapInt { public static void main(String[] agrs){ int m = 12; int n = 5; System.out.println("m:"+m+" n:"+n); m = m + n; //m=12+5 n = m - n; //n=17-5 m = m - n; //m=17-12 System.out.println("m:"+m+" n:"+n);}优点:没有以上两种方法的缺点
public class swapInt { public static void main(String[] agrs){ int m = 12; int n = 5; System.out.println("m:"+m+" n:"+n); m = m ^ n; n = m ^ n;//(m^n)^n == m,相当于m值给n m = m ^ n;//(m^n)^m == n,相当于n值给m System.out.println("m:"+m+" n:"+n);}如图解释:
新闻热点
疑难解答