在 swift 中使用 `**` 作为求幂运算符与 `-` 运算符一起工作不正确
Using `**` as exponentiation operator in swift working incorrectly with the `-` operator
如何使 Swift 中的求幂运算符 **
的行为与其他编程语言中的相同。
问题Exponentiation operator in Swift有以下答案获得最多赞成票,
infix operator ** { associativity left precedence 170 }
func ** (num: Double, power: Double) -> Double{
return pow(num, power)
}
但是,y = -x**2
、
- 被解释为
(-x)**2 = 4.0
(Swift)
- 通常应该解释为
-(x**2) = -4.0
(预期!)
我认为你的问题是:
Unary operators in Swift always take precedence over binary operators.
来源如下:https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc
因此,表达式总是计算为 (-x)**2
而不是 -(x**2)
,因为 -
是一元运算符而 **
是二元运算符。
如何使 Swift 中的求幂运算符 **
的行为与其他编程语言中的相同。
问题Exponentiation operator in Swift有以下答案获得最多赞成票,
infix operator ** { associativity left precedence 170 }
func ** (num: Double, power: Double) -> Double{
return pow(num, power)
}
但是,y = -x**2
、
- 被解释为
(-x)**2 = 4.0
(Swift) - 通常应该解释为
-(x**2) = -4.0
(预期!)
我认为你的问题是:
Unary operators in Swift always take precedence over binary operators.
来源如下:https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc
因此,表达式总是计算为 (-x)**2
而不是 -(x**2)
,因为 -
是一元运算符而 **
是二元运算符。