-4

As per my understanding the operator precedence for the above expression should turn out to be 1 as per PEDMAS but If I declare the whole expression to be a float then the answer is 1.4.

So, which is the right answer 1 or 1.4?

11%2*7/(3+2)? 

 1. (3+2) = 5
 2. 11%2 = 1
 3. Putting all together = 1*7/5 = 1 ans
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • Only trust [the official documentation](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html), and know the difference between integer division and floating point division. – Mike 'Pomax' Kamermans Oct 13 '21 at 00:55
  • 4
    What do you mean "if I declare the whole expression to be a float"? Changing the type of the whole expression doesn't change the computation that happens *inside* it. If you just wrote `(float)` in front of this with no parentheses, then you're only casting the `11`, not the whole expression, and then you *do* get floating-point division. – Silvio Mayolo Oct 13 '21 at 00:58
  • Everything is evaluated left to right. And everything is an **integer**. So everything is integer math. First, `11%2` is `1`. `1 * 7` is `7`. We divide `7` by something. Here precedence means we divide `7` with `5`. That results in `1`. Because we are performing integer math. – Elliott Frisch Oct 13 '21 at 00:59

2 Answers2

1

If you do (float)11%2... you cast the 11 as a float and end up with 11.0%2 using the floating point modulus function, which returns 1.0. Then that 1.0 causes the multiplication to be 1.0*7 which returns 7.0 This causes us to use the floating point division which returns 1.4.

If you want 1 (integer), you need to use (float)(11%2...) to cast the entire result as a float

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
1

So, which is the right answer 1 or 1.4?

Both of them. The two cases you cite are different expressions.

As a programmer, you write the expression you need.

user16632363
  • 1,050
  • 3
  • 6