Exponentiation operator in Swift

后端 未结 9 1161
天命终不由人
天命终不由人 2020-12-13 22:45

I don\'t see an exponentiation operator defined in the base arithmetic operators in the Swift language reference.

Is there really no predefined integer or float ex

相关标签:
9条回答
  • 2020-12-13 23:41

    I did it like so:

    operator infix ** { associativity left precedence 200 }
    
    func ** (base: Double, power: Double) -> Double {
        return exp(log(base) * power)
    }
    
    0 讨论(0)
  • 2020-12-13 23:42

    There isn't an operator but you can use the pow function like this:

    return pow(num, power)
    

    If you want to, you could also make an operator call the pow function like this:

    infix operator ** { associativity left precedence 170 }
    
    func ** (num: Double, power: Double) -> Double{
        return pow(num, power)
    }
    
    2.0**2.0 //4.0
    
    0 讨论(0)
  • 2020-12-13 23:45

    Like most of the C-family of languages, there isn't one.

    0 讨论(0)
提交回复
热议问题