我正致力于在Swift中编写基本的递归函数。该函数正在完美地计算输入的阶乘,但是当我尝试计算20的数字的阶乘时,我遇到了溢出错误。
我已阅读有关错误处理https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html的Apple文档,但我还未能成功将 guard 关键字集成到递归函数中。
func factorial(number: Int) -> Int {
if (number <= 1){
return 1
} else {
return factorial(number: number - 1) * number
}
}
factorial(number: 0) *1*
factorial(number: 1) *1*
factorial(number: 5) *120*
factorial(number: 20) *2432902008176640000*
factorial(number: 21) *error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=...*
任何建议都会很棒!