-1

I have the following expression in my code

int n = ((int) Math.sqrt(4 * 4 + 5) - 1) / 2;

Can someone tell me the precedence in which the expression is evaluated?

Logically I would evaluate the expression in the following way:

  1. 4 * 4 + 5 = 16 + 5 = 21

  2. Math.sqrt(21) ~ 4.58

  3. 4.58 - 1 = 3.58

  4. (int) 3.58 = 3

  5. 3 / 2 = 1.5

However the code evaluates to 1.

  • Did you google "java operator precedence" already? Please do some research before posting here ([oracle tutorial](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)). – Zabuzard Mar 29 '19 at 23:04
  • Yes I did but it did not help me because the problem was integer division (step 5) and not precedence. – CuriousIndeed Mar 30 '19 at 14:50
  • Right. But then you could have precised your question and not ask for precedence :) You should also state such things to show research effort. Else you might get down-voted for lack of research. – Zabuzard Mar 30 '19 at 19:50
  • I honestly thought the problem was precedence. So would it be better just to ask whats wrong with the code? – CuriousIndeed Mar 30 '19 at 20:15

2 Answers2

3

You almost got it. The only difference (which doesn't matter for the result) is that the cast is evaluated before the subtraction, and you're using integer division:

  1. 4 * 4 + 5 = 16 + 5 = 21
  2. Math.sqrt(21) ~ 4.58
  3. (int) 4.58 = 4 (cast first)
  4. 4 - 1 = 3
  5. 3 / 2 = 1 (integer division)
that other guy
  • 116,971
  • 11
  • 170
  • 194
-1

The order you suggest is correct.
The keypoint is the last operation: the result of an int divided by an int is an int as well.
To fix this, one of the two number should be a float (or a double):

float n = ((float)(int) (Math.sqrt(4 * 4 + 5) - 1)) / 2;

In this way you divide a float by an int, and the result will be a float. Or better:

double n = (Math.sqrt(4 * 4 + 5) - 1) / 2;

Because the cast to int of Math.sqrt() isn't useful.
Please note that the first operation does exactly what you ask with the round of the Math.sqrt(), while the second one doesn't.

A. Wolf
  • 1,309
  • 17
  • 39