简体   繁体   English

操作顺序C#

[英]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 因此,步骤将是:v1 + 10 *(v2-- / 5)+ v3 / v2

  1. (v2-- / 5)= 1.4, v2 is then set to 6. (v2-- / 5)= 1.4,然后将v2设置为6。
  2. v3 / v2 = 3 v3 / v2 = 3
  3. 10 * (v2-- / 5) = 14 10 *(v2-- / 5)= 14
  4. 5 + (14) +(3) = 12 5 +(14)+(3)= 12

Therefore, (ans += 12) = 22? 因此,(ans + = 12)= 22?

v2-- / 5)= 1.4 and there is your problem. v2-- / 5)= 1.4 ,这就是您的问题。 Integer division will never return a non integer value. 整数除法永远不会返回非整数值。

1/2 equals 0 , not 0.5 and 7/5 equals 1 , not 1.4 . 1/2等于0 ,而不是0.57/5等于1 ,而不是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. Martin:步骤1是不正确的,因为两个变量都是整数,结果将是整数(v2-- / 5)=1。要得到1.4的答案,则需要将变量更改为double类型。 "So you are effectively left with 10 += 5 + 10 * 1 + 3= 28" “因此,实际上剩下10 + = 5 + 10 * 1 + 3 = 28”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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