为什么Ruby`**`运算符的优先级比一元`-`高? [英] Why does Ruby `**` operator have higher precedence than unary `-`?

查看:100
本文介绍了为什么Ruby`**`运算符的优先级比一元`-`高?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会导致如下情况:

-1 ** 0.5 #=> -1

只有括号可以纠正:

(-1) ** 0.5 #=> 6.123031769111886e-17+1.0i

比预期的1.i差,但基本上可以接受.在我去Ruby bug抱怨之前,我想知道是否有某种原因会导致这种情况?

which is less favorable then expected 1.i, but basically acceptable. Before I go to Ruby bugs to complain, I would like to know whether there is perhaps some reason for this to be so?

推荐答案

许多语言通过按照数学的运算顺序进行建模来定义其运算符优先级表.在数学中,幂运算的优先级确实比乘法高,而一元否定 毕竟是乘法.

Many languages define their operator precedence tables by modeling after mathematics' order of operations. In math, exponentiation does have higher precedence than multiplication, and unary negation is a multiplication, after all.

回复中的matz到省略了数字符号平方时":

From matz in a reply to "the sign of a number is omitted when squaring it":

具有数学背景的人要求具有**的优先权 高于一元减法.这就是原因.

People with mathematical background demands precedence for ** being higher than that of unary minus. That's the reason.

这篇关于为什么Ruby`**`运算符的优先级比一元`-`高?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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