【问题标题】:Using `**` as exponentiation operator in swift working incorrectly with the `-` operator在 swift 中使用 `**` 作为幂运算符与 `-` 运算符一起工作不正确
【发布时间】:2015-04-20 15:50:22
【问题描述】:

如何使 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(预期!)

【问题讨论】:

    标签: swift operator-overloading


    【解决方案1】:

    我相信你的问题是:

    Swift 中的一元运算符总是优先于二元运算符。

    来源:https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc

    因此,表达式始终计算为(-x)**2 而不是-(x**2),因为- 是一元运算符,** 是二元运算符。

    【讨论】:

    • 谢谢!我可能会为此填写一个功能请求。
    • 好主意,很高兴看到运算符按您期望的顺序进行评估!
    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2015-01-12
    • 2018-06-08
    相关资源
    最近更新 更多