Operator Priority in C

Having trouble understanding this expression:

(x + y - 1) / y * y

The priority of the operators is as follows (according to my understanding of K & R2, table 2.12, table 2.1):

1) evaluate what is in parens: firstly (x + y), then (x + y) -1

2) The operator '*' has a higher priority than '/', so it should go first, the bit indicates that (y * y) is evaluated, and then the result (x + y-1) is divided by the product (y * y ) I don’t quite understand.

3) I have ever heard that iw is usually rounded, written in this form:

(x + y - 1) / y * y

It is right? Thank you so much in advance!

+3
source share
6 answers

, "*" "/" , . :

( ( ( (x + y) - 1) / y) * y)
+4

* , /, .

* / .

+6

, * / . ( " precedence", "" )

(x + y - 1) / y * y

( ( (x+y) - 1 ) / y ) * y

:

           *
          / \
         /   y
        ÷
       / \
      /   y
     -
    / \
   /   1
  +
 / \
x   y
+5

1) right

2) , "/" "*" - . , .

3) , "". , :

y = 2, x = 2

(x + y -1)/y * y = (2 + 2 - 1)/2 * 2 = (3/2) * 2 = 1 * 2= 2

3/2 = 1, .

+2

'*' , '/'

. * / -.

:

(x + y - 1) / y * y = z / y * y      // where z = x + y -1

                    = (z / y) * y    // because of associativity.
+1

, , / * . , (x + y + 1).

, (x + y + 1)/(y * y), , , .

, .

Regarding the use of ((x + y-1) / y) * y to round up or down, as it may be, this is a dubious and not very portable practice. Several reasons: 1 / you should know or remember that y is a kind of int, 2 / x should also be a kind of int, 3 / the results may vary depending on the compiler.

0
source

Source: https://habr.com/ru/post/1781380/


All Articles