在某些情况下,我需要在Java中进行非常精确的计算,但它总是会出现一些意外错误.如何避免它们或将错误保持在可接受的范围内?
例如
public static void main(String[] args) throws Exception {
double x = 0.0;
while (x <= 1.0){
System.out.println(x);
x += 0.1;
System.out.println("add 0.1");
}
}
- the result will be
0.0 add 0.1
0.1 add 0.1
0.2 add 0.1
0.30000000000000004 add 0.1
0.4 add 0.1
0.5 add 0.1
0.6 add 0.1
0.7 add 0.1
0.7999999999999999 add 0.1
0.8999999999999999 add 0.1
0.9999999999999999 add 0.1
Run Code Online (Sandbox Code Playgroud)
这不是预期的.
提前致谢
java ×1