Problem in precedence of operators.
-
What number will z in the sample code given below? int z, x=5, y= -10, a=4, b=2; z=x++ - --y *b/a; Can anyone please solve it and explain the precedence. i am not getting right answer. :(( my answer is 2.5. but it is wrong. i am struggling in it. kindly solve it and explain. Thanks in advance. :)
-
What number will z in the sample code given below? int z, x=5, y= -10, a=4, b=2; z=x++ - --y *b/a; Can anyone please solve it and explain the precedence. i am not getting right answer. :(( my answer is 2.5. but it is wrong. i am struggling in it. kindly solve it and explain. Thanks in advance. :)
-
What number will z in the sample code given below? int z, x=5, y= -10, a=4, b=2; z=x++ - --y *b/a; Can anyone please solve it and explain the precedence. i am not getting right answer. :(( my answer is 2.5. but it is wrong. i am struggling in it. kindly solve it and explain. Thanks in advance. :)
See C++ Operator Precedence - cppreference.com[^]. The first step is inserting parentheses according to the predence and order:
z = (x++) - (((--y) * b) / a);
Then replace the variables with their values:
z = (5++) - (((--(-10)) * 2) / 4);
Now solve step by step but observe the special handling of the postfix operator which will return a temporary copy that contains the value before the operation (that means
x
will be changed but the initial value of 5 is used for the calculation). Observe also that results might get rounded wirh integer arithmetic:z = (5) - ((-11 * 2) / 4);
z = 5 - (-22 / 4);
// The remaining steps are left to your exercise -
z=x++ - --y *b/a;
x(++) - ((--y) *b / a);
5 - (-11 * 2 / 4)
5 - (-22 / 4)
5 - (-5) // integer arithmetic ignores remainder
10See C++ Built-in Operators, Precedence and Associativity[^].
thank you. i am clear now
-
What number will z in the sample code given below? int z, x=5, y= -10, a=4, b=2; z=x++ - --y *b/a; Can anyone please solve it and explain the precedence. i am not getting right answer. :(( my answer is 2.5. but it is wrong. i am struggling in it. kindly solve it and explain. Thanks in advance. :)
parkavikkk wrote:
int z, x=5, y= -10, a=4, b=2; z=x++ - --y *b/a; Can anyone please solve it and explain the precedence. i am not getting right answer. :(( my answer is 2.5. but it is wrong.
Of course it is wrong! Just because the integer number cannot be 2.5, nor 2.7, nor 2.8... :cool:
-
parkavikkk wrote:
int z, x=5, y= -10, a=4, b=2; z=x++ - --y *b/a; Can anyone please solve it and explain the precedence. i am not getting right answer. :(( my answer is 2.5. but it is wrong.
Of course it is wrong! Just because the integer number cannot be 2.5, nor 2.7, nor 2.8... :cool: