Java除运算异常

时间:2015-02-04 15:16:55

标签: java divide

给出以下代码:

  long testNum = 1000;
  double midNum = testNum/60000;
  System.out.println(midNum);
  long another = Math.round(7600/midNum);
  System.out.println(another);

输出结果为:

0.0
9223372036854775807
  1. 为什么第一个输出是0.0?我怎样才能在java中得到正确的结果?
  2. 由于第一个输出是0,为什么下一个表达式有结果?不应该抛弃by zero表达式吗?

4 个答案:

答案 0 :(得分:6)

  

为什么第一个输出是0.0?

您正在使用整数除法,因此这是正确的结果。

  

我怎样才能在java中获得正确的结果?

不要使用整数除法,而是使用浮点,这是使其中一个值成为浮点的最简单方法。

double midNum = testNum/60000.0;

double midNum = testNum/60e3;
  

由于第一个输出为0,为什么下一个表达式有结果?

浮点运算使用IEEE-754标准(有时称为IEEE-753.99999999999998;) 在浮点数中,您永远不会在Java中获得异常,您可能会得到无穷大,负无穷大或NaN。

整数没有Infinity或NaN,也无法代表这一点,因此产生了异常。

当您对long的任何数字过大时,它会为您提供最接近的可呈现值,即Long.MAX_VALUE

顺便说一句

long l = Math.round(Double.POSITIVE_INFINITY); // l == Long.MAX_VALUE
long l = Math.round(Double.NEGATIVE_INFINITY); // l == Long.MIN_VALUE
long l = (long) Double.NaN; // l == 0

Double你可能会发现这很有趣。

public final class Double extends Number implements Comparable<Double> {
    /**
     * A constant holding the positive infinity of type
     * {@code double}. It is equal to the value returned by
     * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
     */
    public static final double POSITIVE_INFINITY = 1.0 / 0.0;

    /**
     * A constant holding the negative infinity of type
     * {@code double}. It is equal to the value returned by
     * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
     */
    public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

    /**
     * A constant holding a Not-a-Number (NaN) value of type
     * {@code double}. It is equivalent to the value returned by
     * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
     */
    public static final double NaN = 0.0d / 0.0;

    /**
     * A constant holding the largest positive finite value of type
     * {@code double},
     * (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>.  It is equal to
     * the hexadecimal floating-point literal
     * {@code 0x1.fffffffffffffP+1023} and also equal to
     * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
     */
    public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308

答案 1 :(得分:0)

long是不能保持小数。 Long等于具有更高范围的int。

你应该使用decimal或float。

答案 2 :(得分:0)

您的第一个结果是0.0的原因是由于您使用了隐式转换。当将long除以数字时,Java假定该数字是相同类型并且将执行“长”除法,其没有余数。由于1000/60000介于0和1之间,因此结果有效地被置于0,并且当它是双精度时转换为0.0。您可以通过将行更改为double midNum = testNum/60000D;

来解决此问题

注意末尾的“D”,表示60000是双倍的。这将强制将长期投射为双倍并给出正确的结果。

对于第二部分,你基本上除以一个非常小的数字,使它看起来非常大。 0.0无法通过double精确表示,因此您实际上除以略高于0.0的值,当您修复其他部分时,这将被修复。

答案 3 :(得分:0)

使用类型转换运算符。  double midNum =(double)testNum / 60000;