Search code examples
c#operator-precedence

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?


Solution

  • 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.