![](/img/trans.png)
[英]How to find the difference of two numbers and the absolute value of that answer without using math.abs function JAVA
[英]How do you find if a number is within a range in Java? Problems with Math.abs(num1-num2) <= inRange
我在另一個問題中看到,找到您的號碼是否在一個范圍內的解決方案是,
Math.abs(num1-num2) <= inRange
其中 inRange 是您試圖確定它是否在 num2 和 num1 之間的數字。
當我插入這些數字時,這個公式對我來說中斷了。
Math.abs(25-(-25)) <= -5
我試圖找出 -5 是否介於 -25 和 25 之間。即使答案是正確的,這個等式也是錯誤的,-5 介於 -25 和 25 之間。
請為我澄清!
我根本看不出有任何理由使用Math.abs
。 我會用:
if (lowerBound <= value && value < upperBound)
或者
if (lowerBound <= value && value <= upperBound)
如果您希望上限也包含在內。
事實上, Math.abs()
方法似乎完全被破壞了 - 我強烈懷疑你誤解了它作為解決方案提出的問題。
做就是了:
bool isInRange = Math.min(num1,num2) <= inRange
&& Math.max(num1,num2) >= inRange;
您當前的方法只是檢查數字范圍。 實際上最小和最大數距離。
對於獎勵積分,Guava 10.x 中引入了一個新的Range類(與輔助類Ranges 一起使用):
import com.google.common.collect.Range;
import com.google.common.collect.Ranges;
public class RangeTest {
Range<Integer> range = Ranges.closed(-25, +25);
public boolean rangeTest(Integer candidate) {
return range.contains(candidate);
}
}
public class TestMain {
static RangeTest rangeTest = new RangeTest();
public static void doTest(Integer candidate) {
System.out.println(candidate + " in -25..+25: "
+ rangeTest.rangeTest(candidate));
}
public static void main(String[] args) {
doTest(-26);
doTest(-25);
doTest(-24);
doTest(-1);
doTest(-0);
doTest(+1);
doTest(+24);
doTest(+25);
doTest(+26);
}
}
輸出:
-26 in -25..+25: 假
-25 in -25..+25: 真
-24 in -25..+25: true
-1 in -25..+25: 真
-25..+25 中的 0:真
-25..+25 中的 1:真
24 in -25..+25: true
25 in -25..+25: true
26 in -25..+25: 假
Range 類支持開和閉范圍,范圍從 -INF 到 +INF,以及各種與范圍相關的操作,如成員資格、交集和跨度。
下面的表達式將檢查x
是否在a
和b
之間:
Math.abs(x - a) + Math.abs(b - x) == Math.abs(b - a)
老問題,但是 Math.abs 方法可以根據您正在處理的內容更清晰,並且仍然值得展示:
int x = 5;
int bounds = 25;
if(Math.abs(x) <= bounds) {
//run if x is anywhere between -25 and 25
}
kotlin 有 .. 運算符
if (center.x in 0..MaxX) {
//Do stuff
}
if (center.y !in 0..MaxY) {
//Do stuff
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.