有没有办法在不使用java中的Math.abs()方法的情况下找到一个数字的绝对值。
发布于 2012-06-13 19:00:12
如果你深入研究Math.abs,你可能会找到最好的答案:
例如,对于浮点数:
/*
* Returns the absolute value of a {@code float} value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
* Special cases:
* <ul><li>If the argument is positive zero or negative zero, the
* result is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
*/
public static float abs(float a) {
return (a <= 0.0F) ? 0.0F - a : a;
}
发布于 2012-06-13 18:44:27
是:
abs_number = (number < 0) ? -number : number;
对于整数,这可以很好地工作(除了Integer.MIN_VALUE
,它的绝对值不能表示为int
)。
对于浮点数来说,事情就更加微妙了。例如,这个方法--以及到目前为止发布的所有其他方法--将不能正确处理negative zero。
为了避免自己处理这些微妙的问题,我的建议是坚持使用Math.abs()
。
发布于 2012-06-13 18:44:03
如下所示:
if (number < 0) {
number *= -1;
}
https://stackoverflow.com/questions/11013187
复制相似问题