9

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!

3 Answers3

25

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.

NPE
  • 464,258
  • 100
  • 912
  • 987
6

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.

Benjamin Gruenbaum
  • 260,410
  • 85
  • 489
  • 489
3

The decimal portion of ints 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.

0x6C38
  • 6,583
  • 4
  • 34
  • 47