Skip to content

Latest commit

 

History

History
85 lines (63 loc) · 2.43 KB

File metadata and controls

85 lines (63 loc) · 2.43 KB

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

原文: https://beginnersbook.com/2017/09/java-program-to-find-largest-of-three-numbers/

在这里,我们将编写两个 java 程序来查找三个数字中最大的程序。 1)使用if-else..if2)使用嵌套的If

要了解这些程序,您应该掌握 Java 中if..else-if语句的知识。如果您是 java 新手,请从核心 Java 教程开始。

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

public class JavaExample{

  public static void main(String[] args) {

      int num1 = 10, num2 = 20, num3 = 7;

      if( num1 >= num2 && num1 >= num3)
          System.out.println(num1+" is the largest Number");

      else if (num2 >= num1 && num2 >= num3)
          System.out.println(num2+" is the largest Number");

      else
          System.out.println(num3+" is the largest Number");
  }
}

输出:

20 is the largest Number

示例 2:使用嵌套if在三个数字中查找最大数字

public class JavaExample{

   public static void main(String[] args) {

      int num1 = 10, num2 = 20, num3 = 7;

      if(num1 >= num2) {

	  if(num1 >= num3)
		/* This will only execute if conditions given in both
		 * the if blocks are true, which means num1 is greater
		 * than num2 and num3
		 */
		System.out.println(num1+" is the largest Number");
	  else
	        /* This will only execute if the condition in outer if
		 * is true and condition in inner if is false. which
		 * means num1 is grater than num2 but less than num3.
		 * which means num3 is the largest
		 */
		System.out.println(num3+" is the largest Number");
      } 
      else {

	  if(num2 >= num3)
		/* This will execute if the condition in outer if is false
		 * and inner if is true which means num3 is greater than num1
		 * but num2 is greater than num3\. That means num2 is largest
		 */
		System.out.println(num2+" is the largest Number");
	  else
		/* This will execute if the condition in outer if is false
		 * and inner if is false which means num3 is greater than num1
		 * and num2\. That means num3 is largest
		 */
		System.out.println(num3+" is the largest Number");
      }
   }
}

输出:

20 is the largest Number