如何以Swift语言获得一些整数的权力? [英] How to get the Power of some Integer in Swift language?

查看:133
本文介绍了如何以Swift语言获得一些整数的权力?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我想得到一些类似于

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆