温馨提示:本文翻译自stackoverflow.com,查看原文请点击:double - How to get the Power of some Integer in Swift language?
swift integer double pow

double - 如何在Swift语言中获得某些整数的力量?

发布于 2020-03-27 11:26:13

我最近学的很快,但是我有一个基本问题,找不到答案

我想得到像

var a:Int = 3
var b:Int = 3 
println( pow(a,b) ) // 27

但是pow函数只能使用双数,不能使用整数,而且我什至无法将int转换为Double(a)或a.double()之类的东西。

为什么它不提供整数的幂?它一定会毫无疑问地返回一个整数!为什么不能将整数转换为双精度?只需将3更改为3.0(或3.00000 ...即可)

如果我有两个整数,并且想进行幂运算,该如何顺利进行?

谢谢!

查看更多

查看更多

提问者
林鼎棋
被浏览
201
Grimxn 2016-09-20 16:04

如果愿意,可以声明一个infix operator

// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8

我使用了两个插入符号,因此仍然可以使用XOR运算符

Swift 3更新

在Swift 3中,“魔术数字” precedence被替换为precedencegroups

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8