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
Asked
Active
Viewed 175 times
0
-
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 Answers
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
-
I'm such an idiot, I completely forgot it stay an int, thanks so much. – Joe Swindells Dec 03 '20 at 22:09
-
-
Add to the answer how to go around this by casting (implicit or explicit). – Everyone Dec 03 '20 at 22:12
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