Let’s say we have this kind of loop (pseudocode)
double d = 0.0
for i in 1..10 {
d = d + 0.1
print(d)
}
In C with printf("%f", d) I get this:
0.100000
0.200000
0.300000
...
1.000000
In C++ with cout << d I get this:
0.1
0.2
...
1
In Java with System.out.println(d) I get this:
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
So my questions are these:
- Why is this simple code printed in Java so badly and is correct in C?
- How does this behave in other languages?
Since you are not comparing the same operations, you will get different result.
The behaviour of
doubleis exactly the same across different languages as it uses the hardware to perform these operations in each case. The only difference is the methods you have chosen to display the result.In Java, if you run
it prints
If you run
you get