2013-07-31 27 views
0

這裏是我簡單的方程式計數器。現在它計算有兩個變量的方程式。它基於嘗試ab變量的許多組合(4千萬或16千萬)。因此,代碼運行良好, 。但是因爲我試圖將變量b加倍,所以事情出錯了。我預計b=b+0.1行將第10次設置變量b設置爲1.0。但是在啓動後幾乎馬上會出現更多小數,因此每個b都會出現。所以,我使用錯誤的數據類型?或者我應該通過不同的值提高變量b?(我也嘗試將所有變量改爲雙倍)。感謝您的建議!Java-雙變量問題

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class Buffer{ 
static int a; 
static double b; 
static BufferedReader reader; 
static String query; 
static int range; 
static int result; 

public static void main(String[] args)throws IOException{ 
    reader=new BufferedReader(new InputStreamReader(System.in)); 

    System.out.print("Choose speed of test(fast or slow):"); 
    query=reader.readLine(); 

    if(query.equals("fast")) 
     range=2000; 
    else 
     range=4000; 

    //START THE TEST//  
    while((a+b)!=26000){ 
     b=b+0.1; 
     if(b==range+1){ 
      b=0; 
      a=a+1; 
     } 
     if((a+b)!=26000) 
      System.out.println("a- "+a+", "+"b- "+b+"=false."); 

     if((a+b)==26000){ 
      System.out.println("a- "+a+", "+"b- "+b+"=true."); 
      System.out.println("\n"+"Done.You can possibly solve this equation, if a= "+a+" and b= "+b+"."); 
     } 
     if(a==range&&b==range&&(a+b)!=26000){ 
      System.out.println("\n"+"Tested "+a*b+" options.Solution not found."); 
      System.exit(0); 
     } 
    } 
} 
} 
+4

這可以幫助你[雙倍增量在Java](http://stackoverflow.com/questions/13832864/double-increments-in-java) – Smit

+2

恭喜,你是第1,000,000人以[雙精度問題(http://en.wikipedia.org/wiki/Double-precision_floating-point_format)。如果你想要確切的值使用'BigDecimal'。 –

+0

而且,在處理浮點表示時,絕對不要(除非你完全知道你在做什麼)使用'=='比較 - 總是比較'> ='或者做循環索引測試等等。 –

回答

1

您處理的問題是representation error。類型double不能表示一些值。

這種情況的典型解決方案是使用BigDecimal或Integer類型。

1

大家在這裏,確實給你一個替代解決方案,但我認爲你應該明白,爲什麼數據類型double不適合你。

問題在於Binary representation。小數點不表示具體形式。 說,例如:

10 is represented as 1010 in binary

0.10 is 0.00011001100110011001100110011001 and still going on.....

在雙因此發生了錯誤。正如其他人所建議的那樣,選擇BigDecimal。

你也可以通過這些鏈接瞭解更多相同的內容;

Rounding Errors

Addition Of Doubles

希望有所幫助。