如何以Swift语言获得一些整数的权力? [英] How to get the Power of some Integer in Swift language?
问题描述
我想得到一些类似于
var a:Int = 3
var b:Int = 3
println(pow(a,b))// 27
但是pow函数只能使用double数字,不适用于整数,而I甚至不能通过像Double(a)或a.double()...这样的东西来将int加倍。
为什么它不提供整数的幂?它一定会返回一个整数没有歧义!
,为什么我不能把一个整数转换成一个double?它只是将3改为3.0(或3.00000 ... any)
如果我有两个整数,我想做电源操作,我该怎么做顺利?
谢谢!
如果你喜欢,你可以声明一个 infix
运算符
。
//将该文件放在项目的任何位置
中缀运算符^^ {associativity left precedence 160}
func ^^(radix:Int,power:Int) - > Int {
return Int(pow(Double(radix),Double(power)))
}
// ...
//那么你可以做这个...
let i = 2 ^^ 3
// ...或
println(2³= \(2 ^^ 3))//打印2³= 8
我使用了两个插入符,所以你仍然可以使用 XOR运算符。
Swift 3的更新
在Swift 3中,魔术数字优先级
替换为
precedencegroups
:
precedencegroup PowerPrecedence {高级:MultiplicationPrecedence}
中缀运算符^^:PowerPrecedence
func ^^(radix:Int,power:Int) - > Int {
return Int(pow(Double(radix),Double(power)))
}
// ...
//那么你可以做这个...
让i2 = 2 ^^ 3
// ...或
print(2³= \(2 ^^ 3))//打印2³= 8
I'm learning swift recently, but I have a basic problem that can't find an answer
I want to get something like
var a:Int = 3
var b:Int = 3
println( pow(a,b) ) // 27
but the pow function can work with double number only, it doesn't work with integer, and I can't even cast the int to double by something like Double(a) or a.double()...
Why it doesn't supply the power of integer? it will definitely return an integer without ambiguity ! and Why I can't cast a integer to a double? it just change 3 to 3.0 (or 3.00000... whatever)
if I got two integer and I want to do the power operation, how can I do it smoothly?
Thanks!
If you like, you could declare an infix
operator
to do it.
// 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
I used two carets so you can still use the XOR operator.
Update for Swift 3
In Swift 3 the "magic number" precedence
is replaced by 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
这篇关于如何以Swift语言获得一些整数的权力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!