2013-07-31 65 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

希望有所帮助。