示例 1: 使用临时变量交换两个数字
public class SwapNumbers { public static void main(String[] args) { float first = 1.20f, second = 2.45f; System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); // Value of first is assigned to temporary float temporary = first; // Value of second is assigned to first first = second; // Value of temporary (which contains the initial value of first) is assigned to second second = temporary; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } }
输出:
--Before swap-- First number = 1.2 Second number = 2.45 --After swap-- First number = 2.45 Second number = 1.2
在上面的程序中,两个要交换的数字
1.20f
和
2.45f
存储在变量中:
first和
second 分别。
在交换之前使用
首先,first 的值存储在变量 temporary(println()
打印变量,以便在交换完成后清楚地看到结果。
temporary = 1.20f
) 中。
然后,second 的值存储在 first(first = 2.45f
) 中。
并且,最后 temporary 的值存储在 second(second = 1.20f
) 中。
这样就完成了交换过程,变量被打印在屏幕上。
记住,
temporary 的唯一用途是在交换之前保存
first 的值。您也可以在不使用
temporary 的情况下交换数字。
示例 2: 不使用临时变量交换两个数字
public class SwapNumbers { public static void main(String[] args) { float first = 12.0f, second = 24.5f; System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); first = first-second; second = first + second; first = second-first; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } }
输出:
--Before swap-- First number = 12.0 Second number = 24.5 --After swap-- First number = 24.5 Second number = 12.0
在上面的程序中,我们没有使用临时变量,而是使用简单的数学来交换数字。
对于操作来说,存储
(first-second)
很重要。这存储在变量
first 中。
first = first-second; first = 12.0f-24.5f
然后,我们只需 add
second(
24.5f
) 到这个数字-计算出的
first(
12.0f-24.5f
) 来交换号码。
second = first + second; second = (12.0f-24.5f) + 24.5f = 12.0f
现在,
second 持有
12.0f
(最初的值是 first)。因此,我们从交换的
second(
12.0f
) 中减去计算出的
first(
12.0f-24.5f
) 得到另一个交换号码。
first = second-first;
first = 12.0f-(12.0f-24.5f) = 24.5f
交换的数字使用
println()
打印在屏幕上。