Swift有错误:“线程返回-x”在表达评估之前返回国家
所以我在 xcode Playground 中有代码并收到错误 代码错误
这是我的练习做 返回阶乘 创建一个接受整数并返回该整数的阶乘的函数。即,该整数乘以所有正的较低整数。
这是我的代码
func factorial(_ num: Int) -> Int {
var result :Int = 0
for _ in num...1 {
result = num * (num - 1)
}
return result
}
print(factorial(12)) //此行中出现错误
,但在终端中得到此输出:
So i have code in xcode playground and got the error error in code
and this is the excercise i do
Return the Factorial
Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers.
and this is my code
func factorial(_ num: Int) -> Int {
var result :Int = 0
for _ in num...1 {
result = num * (num - 1)
}
return result
}
print(factorial(12)) //error in this line
but in terminal got this output:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案在错误消息中 - 范围的上限必须大于或等于下部。
因此,您需要以不同的方式重写该方法。您的代码也有一个基本缺陷 - 您的数学逻辑是错误的 - 每次都会覆盖结果,而不是累积总数。采用类似的方法来解决问题:
有一种更优雅的方法可以使用递归执行此操作,从而避免了丑陋的
var num = num = num
The answer is in the error message - the upper bound of the range has to be greater than or equal to the lower.
Therefore you'll need to rewrite the method differently. You also have a fundamental flaw in your code - your maths logic is wrong - result will be overwritten every time, rather than accumulating a total. Adopting a similar approach to the question you can do this:
There is a more elegant way of performing this using recursion, which avoids the ugly
var num=num