C arithmetic precedence

127 views Asked by At

I stumbled upon a question about arithmetic precedence in a test and I cannot wrap my head at all around its answer.

float x = 5 % 3 * + 2 - 4.5 / 5 * 2 + 2;

My "understanding" right now is that multiplication must take place first before division and modulus, yet when I try using that approach, the answer is 6.55 instead of 4.20. I tried playing around with the expression (adding brackets here and there), and it turns out that 5 % 3 takes place first before everything else. I just don't understand why since, according to the precedence table I was provided, that shouldn't be the case. Could someone clear this up for me?

3

There are 3 answers

0
rahul shukla On

you can refers this link for more detail http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

0
Eric Gopak On

Please refer to the documentation here.

The precedence of multiplication, division and remainder operators are higher than those of sum and subtraction.

When multiplication, division or remainder operators go one after another, then they are left-associated, meaning they will be executed one by one in the given order.

In your example 5 % 3 will be performed first, then the multiplication (by whatever number there is), then the division 4.5 / 5, then multiplication of the result by 2, and only after all that will the sum and subtraction be performed.

0
Nayuki On

Your C code:

x = 5 % 3 * + 2 - 4.5 / 5 * 2 + 2;

First, unary plus and unary minus has the highest precedence:

x = 5 % 3 * (+ 2) - 4.5 / 5 * 2 + 2;

Second, multiplication, division, and remainder have the same precedence, associated from left to right:

x = ((5 % 3) * (+ 2)) - ((4.5 / 5) * 2) + 2;

Last, addition and subtraction have the same precedence, associated from left to right:

x = ((((5 % 3) * (+ 2)) - ((4.5 / 5) * 2)) + 2);

Now we evaluate the expression:

x = (((2 * (+ 2)) - ((4.5 / 5) * 2)) + 2);
x = (((2 * 2) - ((4.5 / 5) * 2)) + 2);
x = ((4 - ((4.5 / 5) * 2)) + 2);
x = ((4 - (0.9 * 2)) + 2);
x = ((4 - 1.8) + 2);
x = (2.2 + 2);
x = 4.2;