這裏是我簡單的方程式計數器。現在它計算有兩個變量的方程式。它基於嘗試a
和b
變量的許多組合(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);
}
}
}
}
這可以幫助你[雙倍增量在Java](http://stackoverflow.com/questions/13832864/double-increments-in-java) – Smit
恭喜,你是第1,000,000人以[雙精度問題(http://en.wikipedia.org/wiki/Double-precision_floating-point_format)。如果你想要確切的值使用'BigDecimal'。 –
而且,在處理浮點表示時,絕對不要(除非你完全知道你在做什麼)使用'=='比較 - 總是比較'> ='或者做循環索引測試等等。 –