Java 程序:找出三个数字中最大的

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


示例 1:使用 if..else 语句查找三个数中的最大数

public class Largest {

    public static void main(String[] args) {

        double n1 = -4.5, n2 = 3.9, n3 = 2.5;

        if( n1 >= n2 && n1 >= n3)
            System.out.println(n1 + " is the largest number.");

        else if (n2 >= n1 && n2 >= n3)
            System.out.println(n2 + " is the largest number.");

        else
            System.out.println(n3 + " is the largest number.");
    }
}

输出

3.9 is the largest number.

在上面的程序中,三个数字 -4.53.92.5 分别存储在变量 n1n2n3 中。

然后,为了找到最大的数,使用 if else 语句检查以下条件:

  • 如果 n1 大于或等于 n2n3,则 n1 是最大的。
  • 如果 n2 大于或等于 n1n3,则 n2 是最大的。
  • 否则,n3 是最大的。

也可以使用嵌套的 if..else 语句来查找最大的数。


示例 2:使用嵌套 if..else 语句查找三个数中的最大数

public class Largest {

    public static void main(String[] args) {

        double n1 = -4.5, n2 = 3.9, n3 = 5.5;

        if(n1 >= n2) {
            if(n1 >= n3)
                System.out.println(n1 + " is the largest number.");
            else
                System.out.println(n3 + " is the largest number.");
        } else {
            if(n2 >= n3)
                System.out.println(n2 + " is the largest number.");
            else
                System.out.println(n3 + " is the largest number.");
        }
    }
}

输出

5.5 is the largest number.

在上面的程序中,我们使用嵌套的 if 来查找最大的数,而不是在单个 if 语句中检查两个条件。

然后,为了找到最大的数,使用 if else 语句检查以下条件:

  • 如果 n1 大于或等于 n2
    • 并且如果 n1 大于或等于 n3,则 n1 是最大的。
    • 否则,n3 是最大的。
  • 否则,
    • 如果 n2 大于或等于 n3,则 n2 是最大的。
    • 否则,n3 是最大的。

另请阅读

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

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

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

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