Finding absolute value of a number without using Math.abs()

后端 未结 10 1563
轮回少年
轮回少年 2021-02-02 11:16

Is there any way to find the absolute value of a number without using the Math.abs() method in java.

10条回答
  •  故里飘歌
    2021-02-02 12:17

    If you look inside Math.abs you can probably find the best answer:

    Eg, for floats:

        /*
         * 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:
         * 
    • If the argument is positive zero or negative zero, the * result is positive zero. *
    • If the argument is infinite, the result is positive infinity. *
    • If the argument is NaN, the result is NaN.
    * In other words, the result is the same as the value of the expression: *

    {@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; }

提交回复
热议问题