簡體   English   中英

Java除法運算異常

[英]Java divide operation exception

給定以下代碼:

  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表達式嗎?

為什么第一個輸出是0.0?

您正在使用整數除法,因此這是正確的結果。

如何在Java中獲得正確的結果?

不要使用整數除法,而應使用浮點數,這是使值之一成為浮點數的最簡單方法。

double midNum = testNum/60000.0;

要么

double midNum = testNum/60e3;

由於第一個輸出為0,為什么下一個表達式有結果?

浮點算法使用IEEE-754標准(有時稱為IEEE-753.99999999999998)。在浮點中,Java中永遠不會出現異常,您可能會遇到無窮大,負無窮大或NaN。

整數沒有Infinity或NaN,也沒有辦法表示它,因此它產生了Exception。

如果將任何數字舍入得太大了long它將為您提供最接近的可表示值Long.MAX_VALUE

BTW

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

long不能保留小數。 Long等於int,只是具有更大的范圍。

您應該使用小數或浮點數。

您的第一個結果為0.0的原因是由於您使用了隱式強制轉換。 當用數字除以long時,Java假定該數字是同一類型,並且將執行“ long”除法,該除法沒有余數。 由於1000/60000在0到1之間,因此結果有效地下限為0,而當其為兩倍時則強制轉換為0.0。 您可以通過將行更改為double midNum = testNum/60000D;來解決此double midNum = testNum/60000D;

注意末尾的“ D”,表示60000是雙精度。 這將迫使long轉換為double並給出正確的結果。

對於第二部分,基本上是用一個非常小的數字除,使其看起來很大。 0.0不能用雙精度表示,因此實際上是除以略高於0.0的值,該值將在您固定另一部分時固定。

使用類型強制轉換運算符。 double midNum =(double)testNum / 60000;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM