原文: 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.");elseSystem.out.println(n3 + " is the largest number.");}}
运行该程序时,输出为:
3.9 is the largest number.
在上述程序中,三个数字-4.5,3.9和2.5分别存储在变量n1,n2和n3中。
然后,为了找到最大的条件,使用if else语句检查以下条件
- 如果
n1大于或等于n2和n3,则n1最大。 - 如果
n2大于或等于n1和n3,则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.");elseSystem.out.println(n3 + " is the largest number.");} else {if(n2 >= n3)System.out.println(n2 + " is the largest number.");elseSystem.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最大。
- 如果
