More than one way to get the max of 3 numbers.

来源:互联网 发布:淘宝旺旺名怎么设置 编辑:程序博客网 时间:2024/05/18 11:25

//需求:键盘录入三个数据获取最大值

下面是初始方法

public static void main(String[] args) {        // prompt user to enter number        Scanner sc = new Scanner(System.in);        System.out.println("Please enter num 1 :");        int a = sc.nextInt();        System.out.println("Please enter num 2 :");        int b = sc.nextInt();        System.out.println("Please enter num 3 :");        int c = sc.nextInt();        // call the fuction        getMax(a, b, c);    }    private static void getMax(int a, int b, int c) {        // 方法1:if,比武        int max = a;        if (a < b) {            max = b;        }        if (max < c) {            max = c;        }        System.out.println("The max num = " + max);    }

方法2:

int max;        if (a > b) {            if (a > c) {                max = a;            } else {                max = c;            }        } else {            if (b > c) {                max = b;            } else {                max = c;            }        }

方法3:

// 方法2: 三元运算法,两行代码int temp = (a > b) ? a : (b);int max = (temp > c) ? temp : c;

方法4:

// 方法3: 三元运算法,一行代码int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
阅读全文
0 0