2016-04-03 118 views
-3

那麼我有以下程序。這是我的老師給的樂趣。我對結果感到驚訝。Double vs Float - Java

代碼:

public class Testing { 

    public static void main(String[] args) { 

     float  piF = 3.141592653589793f; // value assigned has float precision 
     double piD = 3.141592653589793; // value assigned has double precision 
     final double THRESHOLD = .0001; 
     if(piF == piD) 
      System.out.println("piF and piD are equal"); 
     else 
      System.out.println("piF and piD are not equal"); 
     if(Math.abs(piF - (float) piD) < THRESHOLD) 
      System.out.println("piF and piD are considered equal"); 
     else 
      System.out.println("piF and piD are not equal"); 

    } 

} 

結果:

piF and piD are not equal 
piF and piD are considered equal 

那麼爲什麼PIF和PID不相等?而實際上Math.abs()這樣做是否使兩者相同?

+0

@Pooya它不重複......請閱讀我的問題,它是多樣的。 –

+0

我不知道我的問題爲什麼被低估。請告訴我爲什麼它被低估了。 –

回答

0

我在終端跑了這一點,那麼添加PIF和PID值打印報表和這裏的結果:

piF and piD are not equal 
piF and piD are considered equal 
piF = 3.1415927 
piD = 3.141592653589793 

當你做兩者之間的直接比較,他們是不相等的。但是,當你施放PID號浮點類型,就變成這樣:

(float) piD = 3.1415927 

嘗試使用打印語句上的變量,當你不理解的結果,這是瞭解這個東西,一個偉大的方式!

這裏是打印語句我加供大家參考:

System.out.println("piF = " + piF); 
    System.out.println("piD = " + piD); 

    System.out.println("(float) piD = " + (float) piD);