简体   繁体   中英

C++ order of evaluation: division vs addition

Going over some workbook questions and one asks me to find the output of this:

#include <iostream>

using namespace std;

int main()
{
    int x, y;
    x = 4;
    y = 1;
    while (x < 5) {
        x = x + y / 3;
        y = y + 1;
        cout << "x = " << x << " " << "y = " << y << endl;
    }
    cout << "the sum of x and y is " << x + y << endl;
}

My question is why x = 4 after the first run of this program. I get that [x = 4+1 / 3] is [x = 5/3] therefore 3 goes into 5 one time with remainder 2. Wouldn't the program cout x = 1 y = 2 after the first run of the program instead of x = 4 y = 2?

No parentheses. Division has a higher precedence than addition, ergo:

x = x + y / 3
x = 4 + 1/3

Because 1/3 is truncated to 0.

x = 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM