[英]Java: Max and Min in absolute value
I'm looking for a method that given 2 floats A and B return the value (A or B) with lower absolute value. 我正在寻找一种方法,给出2个浮点数A和B返回具有较低绝对值的值(A或B)。
Initially I tried 最初我试过了
Math.min(Math.abs(A),Math.abs(B));
but it is not correct because for example for (-9,-2) return +2 and the return value I'm looking for is -2. 但它不正确,因为例如(-9,-2)返回+2并且我正在寻找的返回值是-2。
Is there some native/built-in for that? 是否有一些原生/内置?
Math.abs(A) < Math.abs(B) ? A : B;
我不赞成对局部变量使用大写,但是
(Math.abs(A) < Math.abs(B)) ? A : B
Math.min()
returns the lowest of the two parameters passed into it. Math.min()
返回传递给它的两个参数中的最低者。 In the example above, you're providing it with arguments of 999
and 2
(The absolute values generated by Math.abs()
. 在上面的示例中,您将为其提供999
和2
参数( Math.abs()
生成的绝对值。
You could replace the Math.min()
call with something like: 您可以使用以下内容替换Math.min()
调用:
Math.abs(A) < Math.abs(B) ? A : B;
val = (Math.abs(A) < Math.abs(B)) ? A : B;
Well, it's a correct behaviour. 嗯,这是一个正确的行为。
You're getting the absolute value of both numbers inside the Min funcion which returns the minimum value of both. 你得到Min funcion中两个数字的绝对值,它返回两者的最小值。 In your case that's 2 because you're comparing 9 and 2. 在你的情况下是2,因为你比较9和2。
EDIT 编辑
AFAIK There's not built-in way to do what you want to do. AFAIK没有内置的方法可以做你想做的事。 As others have suggested, you have to make the comparation yourself with something like: 正如其他人所建议的那样,你必须自己做一些比较:
Math.abs(A) < Math.abs(B) ? A : B
Just remember to be careful with the types you compare and the result. 记住要小心你比较的类型和结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.