有人可以解释一下我的斐波那契代码的结尾吗?
我正在创建斐波那契,我最初的返回是“return (num - 1) + (num - 2)”,但不起作用,有人建议调用该函数“return fibonacci(num - 1) + fibonacci(num - 2)”它有效,我的问题是为什么?
代码在附件
function fibonacci(num) {
if (num < 2) {
return num;
} else {
return fibonacci(num - 1) + fibonacci(num - 2)
}
}
I was creating fibonacci and my original return was "return (num - 1) + (num - 2)" but dont work, some one sugested to call the function "return fibonacci(num - 1) + fibonacci(num - 2)" and it worked, my question is why?
Code in anex
function fibonacci(num) {
if (num < 2) {
return num;
} else {
return fibonacci(num - 1) + fibonacci(num - 2)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 MDN 中看到,“函数调用自身的行为,递归用于解决包含较小子问题的问题。递归函数可以接收两个输入:基本情况(结束递归)或递归情况(恢复递归) )”。感谢您耐心解释 Parag Diwan。
I see in the MDN, "The act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion)." Thanks for the pacience to explain Parag Diwan.