2015-07-01 33 views
0

我正在執行浮點值比較..以及在下面的程序中。這是一個非常基本的..在比較過程中有小數點的一些技巧。 請幫我理解這一點。比較在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

然後,我已經從所有三個值

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. "); 
     } 
    } 
} 

現在的結果是最後一個數字(9)中除去:圓周率小於3

回答

2

當然,結果是意想不到的。你不應該/不能做精確的浮點比較。

通常,如果你想比較兩個浮點值(A和B),你可以做差異A-B,並將它與可接受的錯誤(比如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 
+1

值得注意的原因。在java中,float是一個單精度64位IEEE 754浮點。這並不意味着要保留精確的小數值,所以總會有誤差。 如果您需要確切的數字或託管的精度,您應該使用BigDecimal。 – lscoughlin