我一直在回答这些 CodingBat 问题,但我遇到了另一个问题。
作业是这样的:
Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range.
一些例子:
- max1020(11, 19) → 19
- max1020(19, 11) → 19
- max1020(11, 9) → 11
我的解决方案是:
public int max1020(int a, int b) {
if (((a >= 10 && a <= 20) || (b >= 10 && b <= 20)) && a >= b) {
return a;
}
if (((a >= 10 && a <= 20) || (b >= 10 && b <= 20)) && b >= a) {
return b;
} else {
return 0;
}
}
该代码在超过一半的时间内返回了正确的输出,但在某些情况下它没有按预期工作。这些场景是当输入为 (10,21)、(21,10)、(23,10) 时。
这很奇怪,因为我明确排除了#>20,但对于上述三种情况,它分别返回 21、21 和 23。
我哪里做错了?
最佳答案
让我们遍历它们。
(10,21):
if(((10 >= 10 && 10 <= 20) || (21>=10 && 21<=20)) && 10>=21)
(((true and true) || (true and false)) && false)
((true) && false)
false
好吧,不是那个。
if(((10 >= 10 && 10 <= 20) || (21>=10 && 21<=20)) && 21>=10)
(((true and true) || (true and false)) && false)
((true) and true)
true
-> return 21
好的,为什么会这样?因为您的逻辑说“如果任一值在范围内,则返回较大的值,即使较大的值不在范围内”。
相反,如果一个值超出范围,甚至不要考虑它。这是一个可能的开始:
if(a < 10 && a > 20) {
// do something with only b. This is where you would return zero, too.
} else if(b < 10 && b > 20) {
// do something with only a
} else {
// do something with both
}
关于java - 在范围内查找更大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367651/