Java程序填空,已知变量a、b的值,要求交换a、b的值并输出到屏幕上

2024-10-31 23:14:14
推荐回答(5个)
回答1:

System.out.println("Before exchange:");
System.out.println("a = " + a);
System.out.println("b = " + b);

// routine to exchange a, b
...

System.out.println("After exchange:");
System.out.println("a = " + a);
System.out.println("b = " + b);

==================================
// routine to exchange a, b
...

直接:
int tmp = a;
a = b;
b = a;

不用中间量:
a = a + b;
b = a - b;
a = a - b;

不用中间量且不担心溢出:使用 bitwise Xor
a = a ^ b;
b = a ^ b;
a = a ^ b;

回答2:

a=a+b;
b=a-b;
a=a-b;

回答3:

int temp = a;

a = b;
b = temp;

回答4:

楼上两种方法都可以,一种是借助中间变量temp,另一种不用中间变量,也有的面试题要求必须不使用中间变量的

回答5:

借口借口借口就共和国