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

2022-09-01 23:58:44

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


答案 1

如果你看看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;
    }

答案 2

是的:

abs_number = (number < 0) ? -number : number;

对于整数,这工作正常(除了 ,其绝对值不能表示为 )。Integer.MIN_VALUEint

对于浮点数,事情更微妙。例如,此方法以及到目前为止发布的所有其他方法将无法正确处理负零

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