簡體   English   中英

比較浮點值會在Java中產生意外結果

[英]Comparing float values giving unexpected results in java

我在下面的程序中執行浮點值比較。 這是非常基本的。.在比較過程中,十進制長度有一些技巧。 請幫助我理解這一點。

class C
{
    public static void main(String args[])
    {
        Float pi = new Float(3.13999999f);
        if (pi > 3.13999999) {
             System.out.print("pi is bigger than 3. ");
        }
        else if (pi < 3.13999999){
            System.out.print("pi is less than 3. ");
        }
    }
}

結果:pi大於3

然后我從所有三個值中刪除了最后一位數字(9)

class C
{
    public static void main(String args[])
    {
        Float pi = new Float(3.1399999f);

        if (pi > 3.1399999) {
          System.out.print("pi is bigger than 3. ");
        }
        else if (pi < 3.1399999){
          System.out.print("pi is less than 3. ");
        }
    }
}

現在的結果是:pi小於3

當然結果是出乎意料的。 您絕對不能/不能做精確的浮點數比較。

通常,如果要比較兩個浮點值(A和B),則要進行差值AB,然后將其與可接受的誤差進行比較(假設為0.00001)。

另一種方法是使用Float.compareTo(Float)方法。

    Float pi = new Float(3.139999f);
    int result = pi.compareTo(new Float(3.139999f));

    if (result == 0) {
        System.out.println("they are equal");
    } else {
        System.out.println("something went wrong");
    }

輸出:

they are equal

暫無
暫無

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

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