计算输出值错误
以下代码输出“3”。我期待“1”。
echo $resultado."\n"; // show 2
$valor = $resultado * ($resultado - 1 / 2);
echo $valor."\n"; // show 3, and should be 1
为什么会出现这种情况?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
因为除法
1 / 2
在运算顺序上优先。所以你确实有这个表达式:你应该添加括号为:
以获得你想要的答案。
Because the division
1 / 2
takes precedence in the order of operations. So you have really have this expression:You should add parenthesis to be:
to get the answer you want.
不,你错了。 / 优先于 - 所以你的行是这样的:
那就是:
No, you're wrong. The / has priority on - and so your line is like:
and that is:
这是因为除法运算符 (
/
) 的优先级高于减法运算符 (-
)。您的表达式按顺序变为:
要纠正您的表达式,请在减法周围插入括号,如下所示:
That's because the division operator (
/
) has a higher precedence than the subtraction operator (-
).Your expression becomes, in order:
To correct your expression, insert parethesis around the subtraction, like this:
/ 优先于 + 或 -
要得到 1 作为结果,你需要使用
The / takes precedence over + or -
To get 1 as a result you need to use
替换表达式中的
$resultado
,您将得到:我的建议是复习基本数学;)
Replacing
$resultado
in the expression, you get:My suggestion is review basic math ;)
将其更改为:
您实际上正在执行
2 * (2 - (1 / 2)
=2 * 1.5
=3
Change it to:
You were effectively doing
2 * (2 - (1 / 2)
=2 * 1.5
=3
2*(2-1/2)
除法运算符的优先级高于减号,因此计算机会这样计算:
2*(2-(1/2)) = 2 * 1.5 = 3
充分使用括号。
2*(2-1/2)
The dividing operator has higher order operator precedence than the minus sign, so the computer will calculate it like this:
2*(2-(1/2)) = 2 * 1.5 = 3
Use parentheses liberally.