java 求两个数较小值
//find smallest among two numbers import java.util.Scanner; public class Numbers { public static void main(String[] args) { int num1, num2; Scanner ip = new Scanner(System.in); System.out.print("Enter num1: "); num1 = ip.nextInt(); System.out.print("Enter num2: "); num2 = ip.nextInt(); if (num1 < num2) System.out.println(num1 + " is smaller that " + num2); else if (num2 < num1) System.out.println(num2 + " is smaller that " + num1); else System.out.println("Both are same"); ip.close(); } } OUTPUT: Enter num1: 35 Enter num2: 45 35 is smaller that 45
2
求三个数中最小值
//find smallest among three numbers import java.util.Scanner; public class Numbers { public static void main(String[] args) { int num1, num2, num3; Scanner ip = new Scanner(System.in); System.out.print("Enter num1: "); num1 = ip.nextInt(); System.out.print("Enter num2: "); num2 = ip.nextInt(); System.out.print("Enter num3: "); num3 = ip.nextInt(); if (num1 >= num2 && num1 >= num3) System.out.println(num1 + " is greater"); else if (num2 >= num1 && num2 >= num3) System.out.println(num2 + " is greater"); else System.out.println(num3 + " is greater"); ip.close(); } } OUTPUT: Enter num1: 5 Enter num2: 6 Enter num3: 6 6 is greater
3
//find smallest among three numbers using ternary operator import java.util.Scanner; public class Numbers { public static void main(String[] args) { int num1, num2, num3, greater; Scanner ip = new Scanner(System.in); System.out.print("Enter num1: "); num1 = ip.nextInt(); System.out.print("Enter num2: "); num2 = ip.nextInt(); System.out.print("Enter num3: "); num3 = ip.nextInt(); // code to find greatest greater = (num1 >= num2 ? (num1 >= num3 ? num1 : num3) : (num2 > num3 ? num2 : num3)); System.out.println("The greatest number is " + greater); ip.close(); } } OUTPUT: Enter num1: 1 Enter num2: 3 Enter num3: 2 The greatest number is 3