您的位置:首页 > 其它

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

2017-06-01 21:37 519 查看
//需求:键盘录入三个数据获取最大值

下面是初始方法

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐