operators precedence in C
have a trouble understanding this expression:
(x + y - 1) / y * y
The operators precedence is as follows (as per my understanding and K&R2, 2.12 table 2.1):
1) evaluate what is in the parens: firstly (x+y), then (x+y) -1
2) '*' operator has higher priority then '/' so it's supposed to go first, bi开发者_开发知识库t it appears that (y * y) is evaluated and then the result of (x+y-1) is divided by the product (y*y). I don't quite get it.
3) I ever heard that normally rounding up iw written in this form:
(x + y - 1) / y * y
Is that correct? Thank you very much in advance!
Unary operator *
has higher precedence than /
, but that is for pointer dereferencing.
Multiplication *
and division /
have the same left-to-right precedence.
no, *
and /
have same precedence. (it is called "precedence", not "priority")
(x + y - 1) / y * y
would be
( ( (x+y) - 1 ) / y ) * y
The operation tree would be:
*
/ \
/ y
÷
/ \
/ y
-
/ \
/ 1
+
/ \
x y
As mentioned earlier the "*" and "/" have the same precedence so they are evaluated left to right. Totally disambiguating the expression gives:
( ( ( (x + y) - 1) / y) * y)
1) right
2) No, "/" and "*" is the same priority. So it will be performed from left to right.
3) I don't understand what your "round up" mean. But for example:
With y = 2, x = 2
(x + y -1) / y * y = (2 + 2 - 1) / 2 * 2 = (3 / 2) * 2 = 1 * 2 = 2
3 / 2 = 1 because this is the division of integer.
'*' operator has higher priority then '/'
Incorrect. Both *
and /
have equal precedence and are left-associative.
After evaluating the parenthesis expression we have:
(x + y - 1) / y * y = z / y * y // where z = x + y -1
= (z / y) * y // because of associativity.
I may be wrong, but as far as I recall / and * have same precedence. So the result should be (x+y+1).
Maybe you should say (x+y+1)/(y*y) if that's what you want the result to be.
It never costs much to disambiguate in any case.
As to using ((x+y-1)/y)*y to round up or down as the case may be, this is a dubious and not very portable practice. Several reasons: 1/ you must know or remember that y is some sort of int, 2/ x must also be some sort of int, 3/ results may vary depending on the compiler.
精彩评论