I have question to everybody.
int a = (int) ((0.7 + 0.1) * 10)
After executing of this code, a = 7. I can`t understand why, because (0.7+0.1)=0.8 and 0.8*10=8. Can anybody tell me why? Thanks!
I have question to everybody.
int a = (int) ((0.7 + 0.1) * 10)
After executing of this code, a = 7. I can`t understand why, because (0.7+0.1)=0.8 and 0.8*10=8. Can anybody tell me why? Thanks!
The issue is that neither 0.1 nor 0.7 can be represented exactly as double
:
0.1
gets represented as approximately 0.10000000000000000555
.
0.7
gets represented as approximately 0.69999999999999995559
.
Their sum is approximately 0.79999999999999993339
. Multiplied by ten and truncated, this gives 7
.
What Every Computer Scientist Should Know About Floating-Point Arithmetic is an excellent read on the subject.
It's float arithmetic, it gets floored.
What's happening here is that (0.1+0.7) is really close to 0.8 but it's not actually 0.8, when you multiply it by 10 you get 7.9999... , when you floor that, you get 7.
The decimal portion of int
s in Java is truncated. You can either make x
and y
floating point variables or just cast them to float and cast them back to get an int as the final result.