跳到主要内容

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.20f2.45f 分别存储在变量 firstsecond 中。

在交换前使用 println() 打印变量,以便在交换后清晰地看到结果。

  • 首先,将 first 的值存储在变量 temporary 中(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("--交换前--");
System.out.println("第一个数字 = " + first);
System.out.println("第二个数字 = " + second);

first = first - second;
second = first + second;
first = second - first;

System.out.println("--交换后--");
System.out.println("第一个数字 = " + first);
System.out.println("第二个数字 = " + second);
}
}

输出

--交换前--
第一个数字 = 12.0
第二个数字 = 24.5
--交换后--
第一个数字 = 24.5
第二个数字 = 12.0

在上述程序中,我们没有使用临时变量,而是使用简单的数学运算来交换数字。

在这个操作中,存储 (first - second) 是重要的。这个值被存储在变量 first 中。

first = first - second;
first = 12.0f - 24.5f

然后,我们只需将 second24.5f)加到计算出的 first12.0f - 24.5f)上来交换数字。

second = first + second;
second = (12.0f - 24.5f) + 24.5f = 12.0f

现在,second 保存了 12.0f(最初是 first 的值)。所以,我们从交换后的 second12.0f)中减去计算出的 first(`12

.0f - 24.5f`)来得到另一个交换后的数字。

first = second - first;
first = 12.0f - (12.0f - 24.5f) = 24.5f

交换后的数字使用 println() 打印在屏幕上。