[英]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
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.5
而7/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.