swift - Swift 中的最大公共(public)指数

标签 swift function integer exponent

我是 Swift 新手,我试图制作一些将任何基数 10 数字转换为不同基数的东西。我首先创建一个函数来查找基数和数字的最大指数值。例如,如果数字是 26,底数是 5,则最大指数将为 2。我创建了该程序,但它总是给我一个错误。我觉得它可能与 Double(num/exponentedBase) 有关,但我不确定。最后,有没有更好的方法来做到这一点。请帮忙。 enter image description here

最佳答案

第一行中的异或运算符与函数第二行中的除法相结合导致了异常。

异或运算符返回一个新数字,当输入位不同时,该数字的位设置为 1;当输入位相同时,该数字的位设置为 0(请参阅 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html,按位异或运算符一章)。

因此,您的变量“exponentedbase”可能为 0,并且您可能尝试除以 0,这会导致异常。

当您打印参数为 12、基数为 2 的GreatestCommonExponent 函数的值时,您将得到以下结果:

first call:
num: 12
base: 2
exponent: 1
exponentedbase: 3

second call:
num: 12
base: 2
exponent: 2
exponentedbase: 0

您应该添加一个保护语句来保存您的代码。 (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120,“提前退出”章节)

编辑: Swift 中的 ^ 运算符是 XOR 函数。语句 2^2 将按位比较数字。

10 XOR 10 = 00

如需进一步引用,请关注https://en.wikipedia.org/wiki/Exclusive_orhttps://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html

如果你想要一个 pow 函数,你应该这样做: How to get the Power of some Integer in Swift language?

这应该适合你:

func greatestCommonExponent(num: Int, base: Int, exponent: Int = 1) -> Int {
    let exponentedbase = base^^exponent
    let value = Double(num/exponentedbase)
    if value > 1 {
        return greatestCommonExponent(num: num, base: base, exponent: exponent+1)
    }
    if value == 1 {
        return exponent
    } else {
        return exponent-1
    }
}

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

greatestCommonExponent(num: 12, base: 2)

12基数2的结果是3

关于swift - Swift 中的最大公共(public)指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39738099/

相关文章:

Swift Xcode 7 beta 5 类型不能将自身作为要求

jsf - h :inputText which is bound to Integer property is submitting value 0 instead of null

c - C中的整数到字符数组的转换

ios - Alamofire 不想在查询中接受我的参数 - 它在调用中说额外的参数

ios - inputAccessoryViewController高度修改

ios - 尝试播放 url 视频文件时,Swift AVPlayer 不断加载

sql-server - 如何在 SQL Server 中加密函数

function - Julia - 定义一个输出函数的函数

javascript - 使用 onkeyup 事件确保电子邮件匹配

将字符数组转换为整数数组