首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在不使用Math.abs()的情况下查找数字的绝对值

在不使用Math.abs()的情况下查找数字的绝对值
EN

Stack Overflow用户
提问于 2012-06-13 18:42:53
回答 9查看 121.8K关注 0票数 21

有没有办法在不使用java中的Math.abs()方法的情况下找到一个数字的绝对值。

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2012-06-13 19:00:12

如果你深入研究Math.abs,你可能会找到最好的答案:

例如,对于浮点数:

代码语言:javascript
复制
    /*
     * 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;
    }
票数 58
EN

Stack Overflow用户

发布于 2012-06-13 18:44:27

是:

代码语言:javascript
复制
abs_number = (number < 0) ? -number : number;

对于整数,这可以很好地工作(除了Integer.MIN_VALUE,它的绝对值不能表示为int)。

对于浮点数来说,事情就更加微妙了。例如,这个方法--以及到目前为止发布的所有其他方法--将不能正确处理negative zero

为了避免自己处理这些微妙的问题,我的建议是坚持使用Math.abs()

票数 19
EN

Stack Overflow用户

发布于 2012-06-13 18:44:03

如下所示:

代码语言:javascript
复制
if (number < 0) {
    number *= -1;
}
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11013187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档