English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习两种在Java中交换两个数字的技术。第一个使用临时变量进行交换,而第二个不使用任何临时变量。
public class SwapNumbers { public static void main(String[] args) { float first = 1.20f, second = 2.45f; System.out.println("--Before swapping--"); System.out.println("premier nombre = ", + first); System.out.println("The second number = ") + second); //first的值被分配给temporary float temporary = first; //second的值被赋给first first = second; //临时的值(包含first的初始值)被赋给second second = temporary; System.out.println("--After swapping--"); System.out.println("premier nombre = ", + first); System.out.println("The second number = ") + second); } }
When running the program, the output is:
--Before swapping-- The first number = 1.2 The second number = 2.45 --After swapping-- The first number = 2.45 The second number = 1.2
在上面的程序中,要交换的两个数字1.20f和2.45f分别存储在变量first和second中。
交换之前使用println()来打印变量,以在交换完成后清楚地看到结果。
首先,first的值存储在临时变量temporary(temporary = 1.20f)中。
然后,second的值存储在first中(first = 2.45f)。
并且,最终的值temporary存储在second(second = 1.20f)中。
这样就完成了交换过程,并且变量被打印在屏幕上。
请记住,temporary的唯一用途是在交换之前保存first的值。您也可以不使用temporary交换数字。
public class SwapNumbers { public static void main(String[] args) { float first = 12.0f, second = 24.5f; System.out.println("--Before swapping--"); System.out.println("premier nombre = ", + first); System.out.println("The second number = ") + second); first = first - second; second = first + second; first = second - first; System.out.println("--After swapping--"); System.out.println("premier nombre = ", + first); System.out.println("The second number = ") + second); } }
When running the program, the output is:
--Before swapping-- The first number = 12.0 The second number = 24.5 --After swapping-- The first number = 24.5 The second number = 12.0
In the above program, we use simple mathematics to swap numbers instead of using a temporary variable.
For the operation, store (first - second) is important. This is stored in the variable first.
first = first - second; first = 12.0f - 24.5f
Then, we just need to add that number onplus second(24.5f)-The calculated first(12.0f - 24.5f) to swap the number.
second = first + second; second = (12.0f - 24.5f) + 24.5f = 12.0f
Now, second holds12.0f (it was originally the value of first). Therefore, we take the swapped second(12.0f) minus the calculated first(12.0f - 24.5f) get the other swapped number.
first = second - first; first = 12.0f - (12.0f - 24.5f) = 24.5f
The swapped numbers are printed on the screen using println().