Floating-point numbers cannot be stored accurately. How to solve the problem when performing equivalence judgment?

For example:
public class T1 { public static void main(String[] args) { double x1 = 0.1; x1=x1+x1+x1+x1+x1+x1+x1+x1+x1+x1; System.out.println (x1); } } The output here is not 1 but 0.9999999. Because floating-point numbers cannot be stored accurately, there will be a certain loss of precision! ! ! ! So how to solve this problem: subtract two values ​​and find the absolute value. If the absolute value is less than a certain value, it is considered equal. Solve the above problem: public class T1 { public static void main(String[] args) { double x1 = 0.1; x1=x1+x1+x1+x1+x1+x1+x1+x1+x1+x1; if(1-x1<1e-6) { System.out.println("Calculation result is: 1") ; //The 1e-6 that is judged here is the value obtained according to the specific situation //It is not fixed } else System.out.println(x1); } }



















Guess you like

Origin blog.csdn.net/qq_45874107/article/details/105655040