乘法和除法的顺序优先 [英] Order precedence of multiplication and division

查看:46
本文介绍了乘法和除法的顺序优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SELECT -1 * 100 / 10
SELECT 100 * -1 / 10

结果不同.第一个返回-10,第二个0.显然是订单造成的.

differ in result. First returns -10, second 0. Obviously it's caused by the order.

但我找不到任何关于除法比乘法权重更高的信息.

But I can't find any information that divisions have higher weighting than multiplications.

查看 http://technet.microsoft.com/en-gb/library/ms190276%28v=sql.105%29.aspx乘法和除法是同一个层次,读上写着

Looking at http://technet.microsoft.com/en-gb/library/ms190276%28v=sql.105%29.aspx multiplication and division are on the same level and reading on it's written

当一个表达式中的两个运算符具有相同的运算符优先级时级别,根据他们在表达.

When two operators in an expression have the same operator precedence level, they are evaluated left to right based on their position in the expression.

关于这一点,第二个查询应该这样评估:100 * -1 ->结果/10,不是吗?

Regarding this, the second query should be evaluated like this: 100 * -1 -> result / 10, shouldn't it?

推荐答案

这要么是文档中的缺陷",要么是 SQL Server 本身的缺陷":根据您的链接,否定运算符 - 有一个运算符优先级低于乘法和除法,但它对计算顺序有影响.您可以看到这一点,因为您仅使用 int 值,因此 -1/10 结果为 0.如果您使用浮点算术,一切都会好起来的:

This is either a "flaw" in the documentation or in SQL Server itself: According to your link the negative operator - has a lower operator precedence than multiplication and division, yet it has an effect on the order of the evaluation. You can see this because you are only using int values so that -1/10 results in 0. If you would use floating point arithmetics everything would be fine:

SELECT -1 * 100 / 10.0
SELECT 100 * -1 / 10.0

或者你可以使用变量来隐藏"否定:

Or you could use variables to "hide" the negate:

DECLARE @a int
DECLARE @b int
DECLARE @c int

SELECT @a=-1, @b=100, @c=10

SELECT @a*@b/@c
SELECT @b*@a/@c

和往常一样,对于复杂的算术(复杂意味着多个运算符),您可以使用括号来强制执行特定的求值顺序,如他的回答中提到的 @Mack.

And as usual with complex arithmetics (complex means more than one operator) you can use parentheses to enforce a certain order of evaluation like @Mack mentioned in his answer.

这篇关于乘法和除法的顺序优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆