Where am I screwing up in the evaluation of this mathematical expression in Java? -


my code is:

int x=5,y=3; x+=y*++x-x/y-y++; system.out.println("value = "+x); 

my evaluation below:

x+=y*++x-x/y-y++
(x=5 | y=3)

x=x+(y*++x-x/y-y++)
(x=5 | y=3) | ++ , -- have highest priority

x=x+(y*6-x/y-3)
(x=6 | y=4) | * , / have next highest priority

x=x+(4*6-(6/4)-3)
(x=6 | y=4)

x=x+(24 -1 -3)
(x=6 | y=4)

x= 6+20
(x=6 | y=4)

x = 26.

however, when evaluate above in java, output turns out 18. did wrong?

additionally, there program online can solve such problems above step step analysis? if so, name some?

the expression evaluated left right :

x += (y*++x)-(x/y) -(y++);       3*6   - 6/3  - 3     == 18 - 2 - 3 == 13 

so

x += 13 == 18 // since original value of x used here 

regarding last part, original value of x used since that's definition of compound assignment operators :

  • first, left-hand operand evaluated produce variable. if evaluation completes abruptly, assignment expression completes abruptly same reason; right-hand operand not evaluated , no assignment occurs.

  • otherwise, the value of left-hand operand saved , right-hand operand evaluated. if evaluation completes abruptly, assignment expression completes abruptly same reason , no assignment occurs.

  • otherwise, the saved value of left-hand variable , value of right-hand operand used perform binary operation indicated compound assignment operator. if operation completes abruptly, assignment expression completes abruptly same reason , no assignment occurs.

  • otherwise, result of binary operation converted type of left-hand variable, subjected value set conversion (§5.1.13) appropriate standard value set (not extended-exponent value set), , result of conversion stored variable.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -