有人可以解释这个代码是如何工作的?它是codeacademy递归js上的代码。该代码使用Fibonacci序列确定增长率。代码输出Fibonacci Beanstalk递归javascript
var height = growBeanstalk(5) // 5
var height = growBeanstalk(8) // 21 etc.
(4) => //3 (3) => //2
预先感谢您!
function growBeanstalk(years) {
// Base case
if (years <= 2) {
return 1;
}
// Recursive case
return growBeanstalk(years - 1)+ growBeanstalk(years - 2);
}
// Set the height of the beanstalk using your function
var height = growBeanstalk();
console.log(height);
[JavaScript的斐波那契崩溃(可能的重复http://stackoverflow.com/questions/18980531/javascript-斐波那契分解) – Prune
堆栈溢出有许多很好的解释递归使用斐波那契序列;几个在JavaScript中。在对这个话题进行研究之后,你对此感到困惑吗? – Prune
例如在growBeanstalk的情况下,我很困惑(8)它给出21,我知道它是8 + 13,但是为什么以及在哪里陈述?为什么直到5返回5,6 => 8,7 => 13。为什么6返回8? –