0

I've been trying to understand java operator precedence but I can't wrap my head around this equation someone has given to me. By adding parentheses myself I get (((78 / 10) * 10) + 10) - 78 but this shouldn't equate to 2. Can someone explain this to me? Thanks

  • Because it is, int division will truncate. The parenthesis are unnecessary. If you want the mathematically correct answer use `float` or `double`: `78.0 / 10 * 10 + 10 - 78`, the `.0` in the first term will ensure it's done using `double` (or `float`?, check documentation) instead of `int`. – Everyone Dec 03 '20 at 22:10

2 Answers2

1
78 / 10 = 7
7 * 10 = 70
70 + 10 = 80
80 - 78 = 2

remember an int /int will be an int

a float / int will be a float so you could do the following:

(float)78 / 10 * 10 + 10 - 78 or 78.0 / 10 * 10 + 10 - 78
DCR
  • 14,737
  • 12
  • 52
  • 115
0

It's because in integer math 78 / 10 is 7, not 7.8

Then:

 7 * 10 = 70
   + 10 = 80
   - 78 =  2
Alnitak
  • 334,560
  • 70
  • 407
  • 495