简体   繁体   中英

Java- double variable issue

Here's my simple equations counter.Now it counts equations with two variables.It's based on trying many combinations (4 milion or 16 milion) of a and b variables.So the code works well and it counts exact.But since I tried to change variable b to double, things go wrong.I've expected line b=b+0.1 secures setting variable b each 10th time to 1.0.But almost imidiately after start way more decimal numbers appear for each b .So do I use wrong datatype? Or should I raise variable b by different value?(I also tried changing all variables to double).Thank you for suggestions!

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);
        }
    }   
}
}

You can use BigDecimal instead of float/double primitives to avoid those issues. Some of which are described here: Java Mistake 1 - Using float and double for monetary or financial calculation

The issue you deal with is representation error . Type double can not represent some values.

Typical solution for this situation is usage of BigDecimal or Integer type.

Everyone here, did give you an alternative solution, but I think you should understand, why did the datatype double did not work for you.

The problem lies with Binary representation . For decimals is not represented to the exact form. Say for example:

10 is represented as 1010 in binary but ,

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

Hence the error occurs in double. As suggested by others, opt for BigDecimal.

You can also learn more about the same, through these links;

Rounding Errors

Addition Of Doubles

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM