Java 程序:交换两个数字

要理解此示例,您应了解以下Java编程主题


示例 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.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("--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

然后,我们只需将 second (24.5f) 加上 这个数字——计算出的 first (12.0f - 24.5f) 来交换数字。

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

现在,second 保存了 12.0f (这是最初 first 的值)。因此,我们将计算出的 first (12.0f - 24.5f) 从已交换的 second (12.0f) 中减去,以获得另一个交换后的数字。

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

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


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战