简体   繁体   中英

Order of operations c#

I'm struggling with understanding why the following returns this value. Any help would be appreciated.

int ans = 10, v1 = 5, v2 = 7, v3 = 18;
ans += v1 + 10 * (v2-- / 5) + v3 / v2;
Console.WriteLine(ans);// prints 28

My thinking would be brackets first, division, multiplication then addition. So the steps would be: v1 + 10 * (v2-- / 5) + v3 / v2

  1. (v2-- / 5)= 1.4, v2 is then set to 6.
  2. v3 / v2 = 3
  3. 10 * (v2-- / 5) = 14
  4. 5 + (14) +(3) = 12

Therefore, (ans += 12) = 22?

v2-- / 5)= 1.4 and there is your problem. Integer division will never return a non integer value.

1/2 equals 0 , not 0.5 and 7/5 equals 1 , not 1.4 .

Martin: Step 1. is incorrect because both variables are integers the result will be an integer, (v2-- / 5) = 1. To get the answer of 1.4 one would need to change the variables to type double. "So you are effectively left with 10 += 5 + 10 * 1 + 3= 28"

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