Swift有错误:“线程返回-x”在表达评估之前返回国家

发布于 2025-01-19 00:31:01 字数 441 浏览 1 评论 0原文

所以我在 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:

error in terminal

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰沐子 2025-01-26 00:31:01

答案在错误消息中 - 范围的上限必须大于或等于下部。

因此,您需要以不同的方式重写该方法。您的代码也有一个基本缺陷 - 您的数学逻辑是错误的 - 每次都会覆盖结果,而不是累积总数。采用类似的方法来解决问题:

func factorial(_ num: Int) -> Int {
  var result :Int = 1

  guard num > 0 else {return result}. //0! is 1 not 0
  var num = num
  while num > 0 {
    result *= num
    num -= 1
  }
  return result
}

有一种更优雅的方法可以使用递归执行此操作,从而避免了丑陋的var num = num = num

func fac2(_ num: Int, total: Int = 1) -> Int {
  return num > 0 ? fac2(num-1, total: total * num) : total
}

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:

func factorial(_ num: Int) -> Int {
  var result :Int = 1

  guard num > 0 else {return result}. //0! is 1 not 0
  var num = num
  while num > 0 {
    result *= num
    num -= 1
  }
  return result
}

There is a more elegant way of performing this using recursion, which avoids the ugly var num=num

func fac2(_ num: Int, total: Int = 1) -> Int {
  return num > 0 ? fac2(num-1, total: total * num) : total
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文