将三个数字与Java逻辑三元运算符进行比较?
问题描述:
我想创建一个返回三个值(全部字节)的最小值的方法。这是我的:将三个数字与Java逻辑三元运算符进行比较?
public static byte findSmallestOfThree(byte n1, byte n2, byte n3) {
return n1 > n2 ? n2 : n1 > n3 ? n3 : n1;
}
现在,我遇到的问题是,它并不总是工作。
这里有一些输入,输出:
9, 10, 11 -> 9
10, 9, 11 -> 9
10, 11, 9 -> 9
11, 10, 9 -> 10
正如你可以看到,当我进入11,10,9(按顺序),我得到了10的结果(即使它应该已经9)。
我的逻辑有什么问题?我认为我已经搞砸了三元运营商的东西,但我不知道它是什么...
答
它与三元运营商不是一个错误;这是比较的错误。你的代码说:如果n1> n2,返回n2。因此,在第四个例子中,11> 10,因此它返回10.
您必须将n1与n2和n3进行比较,以了解它是最大还是最小。你真的想要的东西像
return (n1 <= n2) && (n1 <= n3) ? n1 : (n2 <= n3)? n2 : n3
(注:没有实际测试过)
+1
你可以删除'=' – 2012-02-07 00:08:25
答
byte min = n1 < n2 ? n1 : n2;
return min < n3 ? min : n3;
答
这个工作对我来说(我让他们int
更容易测试):
public static int findSmallestOfThree(int n1, int n2, int n3) {
return n1 < n2 ? n1 < n3 ? n1 : n3 : n2 < n3 ? n2 : n3;
}
如果你关心更多关于可读性比速度:
public static int findSmallestOfThree(int n1, int n2, int n3) {
return Math.min(n1, Math.min(n2, n3));
}
下面是一些简单的测试代码:
public static void main(String[] args) {
System.out.println(findSmallestOfThree(9, 10, 11));
System.out.println(findSmallestOfThree(10, 9, 11));
System.out.println(findSmallestOfThree(10, 11, 9));
System.out.println(findSmallestOfThree(11, 10, 9));
System.out.println(findSmallestOfThree(9, 11, 10));
System.out.println(findSmallestOfThree(11, 9, 10));
}
答
要获得最大值出三个数字中,一行的方法:
INT分钟=(一个< b & &一个< C)? a :((b < a & & b < c)?b:c);
答
代码找到最大的三个号码的使用三元运算符:
public class FindGraterUsingTernaryOperator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 3 Numbers to Check the Grater:::");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int result = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
System.out.println("Grater Between 3 Numbers Is::" + result);
}
}
我爱三元运算尽可能未来的家伙;但这种ascii的歪曲很好地说明了为什么三元组不应该像这样链接。当然,我*可以*坐在这里,假装是javacc,并找出嵌套的位置在哪里......但我更愿意看到几个能够解除我职责的el-elses。这里的其他答案表明你精神上混淆了你的比较;当你在一个声明中尝试做太多时,这很容易做到! – yshavit 2012-02-07 00:00:18