您如何查找Java中的数字是否在范围内? Math.abs(num1-num2)< = inRange的问题
我在另一个问题中看到,找到您的电话号码是否在范围内的解决方案是
I've seen in another question that the solution to finding if your number is in a range was,
Math.abs(num1-num2) <= inRange
inRange是您要弄清楚的数字,它是否在num2和num1之间.
Where inRange is the number you are trying to figure out if it is in range between num2 and num1.
当我插入这些数字时,这个公式对我不利.
Where this formula breaks for me is when I insert these numbers.
Math.abs(25-(-25)) <= -5
我试图确定-5是否在-25和25之间.即使答案是正确的,该等式也是错误的,-5则在-25和25之间.
I'm trying to find if -5 is in between -25 and 25. This equation is false even though the answer is true, -5 falls between -25 and 25.
请为我澄清!
我完全没有理由使用Math.abs
.我会用:
I don't see any reason to use Math.abs
at all. I'd use:
if (lowerBound <= value && value < upperBound)
或
if (lowerBound <= value && value <= upperBound)
如果您也希望包含上限.
if you want the upper bound to be inclusive too.
实际上,Math.abs()
方法似乎完全被打破了-我强烈怀疑您误解了将其作为解决方案的问题.
Indeed, the Math.abs()
approach seems entirely broken - I strongly suspect that you misunderstood the question where it was posed as a solution.