您如何查找Java中的数字是否在范围内? Math.abs(num1-num2)< = inRange的问题 [英] How do you find if a number is within a range in Java? Problems with Math.abs(num1-num2) <= inRange

查看:526
本文介绍了您如何查找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.

这篇关于您如何查找Java中的数字是否在范围内? Math.abs(num1-num2)&lt; = inRange的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆