Java-双变量问题

Mat*_*tin 1 java double

这是我的简单方程计数器。现在它计算带有两个变量的方程。它基于尝试ab变量的许多组合(400 万或 1600 万)。所以代码运行良好并且计数准确。但是因为我尝试将变量更改b为 double ,事情出了问题。我预计行b=b+0.1会确保b每 10 次将变量设置为 1.0。但在启动后几乎立即会出现更多的十进制数字b。那么我是否使用了错误的数据类型?或者我应该将变量提高b不同的值?(我也尝试将所有变量更改为双倍)。谢谢您的建议!

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);
        }
    }   
}
}
Run Code Online (Sandbox Code Playgroud)

mar*_*erh 5

您可以使用 BigDecimal 而不是 float/double 原语来避免这些问题。其中一些描述如下:Java 错误 1 ​​- 使用 float 和 double 进行货币或财务计算