这里是我简单的方程式计数器。现在它计算有两个变量的方程式。它基于尝试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'。 –
而且,在处理浮点表示时,绝对不要(除非你完全知道你在做什么)使用'=='比较 - 总是比较'> ='或者做循环索引测试等等。 –