假设我们有这种循环(伪代码)
double d = 0.0
for i in 1..10 {
d = d + 0.1
print(d)
}
在 C 中,printf("%f", d)
我得到了这个:
0.100000
0.200000
0.300000
...
1.000000
在 C++ 中,cout << d
我得到了这个:
0.1
0.2
...
1
在Java中,System.out.println(d)
我得到了这个:
0.1
0.2
0.3 (in debug mode, I see 0.30000000000004 there but it prints 0.3)
...
0.7
0.799999999999999
0.899999999999999
0.999999999999999
所以我的问题是:
- 为什么这个简单的代码在 Java 中打印得如此糟糕并且在 C 中是正确的?
- 这在其他语言中表现如何?