在不使用 Math.abs() 的情况下查找数字的绝对值 [英] Finding absolute value of a number without using Math.abs()
本文介绍了在不使用 Math.abs() 的情况下查找数字的绝对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有什么办法可以不用java中的Math.abs()方法来求一个数的绝对值.
Is there any way to find the absolute value of a number without using the Math.abs() method in java.
推荐答案
如果您查看 Math.abs,您可能会找到最佳答案:
If you look inside Math.abs you can probably find the best answer:
例如,对于浮点数:
/*
* 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;
}
这篇关于在不使用 Math.abs() 的情况下查找数字的绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文