Skip to content

Latest commit

 

History

History
85 lines (59 loc) · 2.4 KB

File metadata and controls

85 lines (59 loc) · 2.4 KB

Java 程序:在三个数字中找到最大值

原文: https://www.programiz.com/java-programming/examples/largest-number-three

在此程序中,您将学习在 Java 中使用if else和嵌套的if..else语句在三个数字中找到最大的数字。

示例 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查找最大条件。

Then, to find the largest, the following conditions are checked using if else statements

  • 如果n1大于或等于n2,则
    • 如果n1大于或等于n3,则n1最大。
    • 否则,n3最大。
  • 否则,
    • 如果n2大于或等于n3,则n2最大。
    • 否则,n3最大。