Java程序交换两个数字
要理解这个示例,你应该具备以下 Java 编程主题的知识:
示例 1:使用临时变量交换两个数字
public class SwapNumbers {
public static void main(String[] args) {
float first = 1.20f, second = 2.45f;
System.out.println("--交换前--");
System.out.println("第一个数字 = " + first);
System.out.println("第二个数字 = " + second);
// 将 first 的值赋给临时变量
float temporary = first;
// 将 second 的值赋给 first
first = second;
// 将临时变量(包含 first 最初的值)的值赋给 second
second = temporary;
System.out.println("--交换后--");
System.out.println("第一个数字 = " + first);
System.out.println("第二个数字 = " + second);
}
}
输出:
--交换前--
第一个数字 = 1.2
第二个数字 = 2.45
--交换后--
第一个数字 = 2.45
第二个数字 = 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
来交换数字。