The*_*eja 19 java absolute-value number-formatting
有没有办法在不使用java中的Math.abs()方法的情况下找到数字的绝对值.
mih*_*imi 54
如果您查看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;
}
Run Code Online (Sandbox Code Playgroud)
NPE*_*NPE 19
是:
abs_number = (number < 0) ? -number : number;
Run Code Online (Sandbox Code Playgroud)
对于整数,这工作正常(除了Integer.MIN_VALUE,其绝对值不能表示为int).
对于浮点数,事情更加微妙.例如,此方法 - 以及到目前为止发布的所有其他方法 - 将无法正确处理负零.
为了避免不得不自己处理这些微妙之处,我的建议是坚持下去Math.abs().
tib*_*tof 13
像这样:
if (number < 0) {
number *= -1;
}
Run Code Online (Sandbox Code Playgroud)
由于Java是一种静态类型语言,我希望一个带有int的abs方法返回一个int,如果它期望一个float返回一个浮点数,对于一个Double,返回一个Double.也许它可以返回双打和双打的盒装或非盒装类型等等.
所以每种类型需要一个方法,但现在你遇到了一个新问题:对于byte,short,int,long,负值的范围比正值大1.
那么应该为该方法返回什么
byte abs (byte in) {
// @todo
}
Run Code Online (Sandbox Code Playgroud)
如果用户在-128上调用abs?您可以随时返回下一个更大的类型,以确保范围适合所有可能的输入值.这将导致长时间存在的问题,其中不存在正常的较大类型,并且使用户在测试后总是将值降低 - 可能是麻烦.
第二种选择是抛出算术异常.这将阻止在已知输入受限的情况下转换和检查返回类型,从而不会发生X.MIN_VALUE.想想MONTH,用int表示.
byte abs (byte in) throws ArithmeticException {
if (in == Byte.MIN_VALUE) throw new ArithmeticException ("abs called on Byte.MIN_VALUE");
return (in < 0) ? (byte) -in : in;
}
Run Code Online (Sandbox Code Playgroud)
"让我们忽略罕见的MIN_VALUE案例"习惯不是一种选择.首先使代码工作 - 然后快速.如果用户需要更快但有缺陷的解决方案,他应该自己编写.最简单的解决方案可能有效:简单但不太简单.
由于代码不依赖于状态,因此该方法可以而且应该是静态的.这允许快速测试:
public static void main (String args []) {
System.out.println (abs(new Byte ( "7")));
System.out.println (abs(new Byte ("-7")));
System.out.println (abs((byte) 7));
System.out.println (abs((byte) -7));
System.out.println (abs(new Byte ( "127")));
try
{
System.out.println (abs(new Byte ("-128")));
}
catch (ArithmeticException ae)
{
System.out.println ("Integer: " + Math.abs (new Integer ("-128")));
}
System.out.println (abs((byte) 127));
System.out.println (abs((byte) -128));
}
Run Code Online (Sandbox Code Playgroud)
我抓住第一个例外,让它进入第二个例子,仅用于演示.
编程中存在一个坏习惯,即程序员对正确代码的关注要快得多.太遗憾了!
如果你很好奇为什么还有一个负值而不是正值,我会给你一个图表.
| 归档时间: |
|
| 查看次数: |
112082 次 |
| 最近记录: |