+ 1

Please help me understand this code!

Hey, I've seen the following challenge but I don't understand the result: #include <iostream> using namespace std; int main() { int a=8; int x=4; int y=++x + (a%x * a/x); cout << y; return 0; } From my understanding, y should be equal to 8, but it's equal to 9 instead: ++x: x = 5 a%x=8%5=3 a/x=8/5=1 3*1=3 5+3=8 Can someone please tell me where my logic is failing here? Thanks, Mickael

8th Sep 2017, 7:45 PM
Mickael Saavedra
Mickael Saavedra - avatar
2 Antworten
+ 4
% * and / have the same operator precedence so they will be evaluated from left to right. x is 5 a is 8 8%5*8/5 8%5=3 3*8=24 24/5=4 5+4=9
8th Sep 2017, 8:31 PM
ChaoticDawg
ChaoticDawg - avatar
0
Thanks! Makes a lot more sense now!
9th Sep 2017, 5:57 AM
Mickael Saavedra
Mickael Saavedra - avatar