gpt4 book ai didi

javascript - 简单的函数返回我在 JavaScript 中没想到的数字

转载 作者:行者123 更新时间:2023-11-28 17:26:55 25 4
gpt4 key购买 nike

我在纸上测试了这个简单的函数。我的答案是 9,但当我回到家 console.log(fib(6)) 游戏时,我的结果是 8。为什么?

我还问了我的教授,他给了我这张图表,但我还是不明白。有什么帮助吗?

fibonacci chart

function fib(num1) {
if (num1 <= 2) {
return num1 = 1;
} else {
return fib(num1 - 1) + fib(num1 - 2);
}
}

console.log(fib(6));

最佳答案

Chart

此图表演示了代码的作用以及从根本上说明斐波那契数是什么。

该图表的工作原理如下:

  1. 图表从 fib(6) 开始.
  2. fib(x) = fib(x - 1) + fib(x - 2) ,然后fib(6) = fib(5) + fib(4)正如图表中向下移动的箭头所示。
  3. 您现在有两个个值包含在您的最终答案中 fib(5)fib(4) 。该图表显示了如何为它们重复上述过程(将它们分成更小的部分)。
  4. 重复步骤 1-3,直到到达 fib(2)fib(1)自动等于 1根据定义
  5. 最后,将所有 1 相加。位于图表底部(共有 8 个)。

这与您的代码一起出现:

function fib(num1) {
// Start with a number (Step 1 on the chart).
if (num1 <= 2) {
// If it is <= 2, return 1 (Step 4 on the chart)
return num1 = 1;
} else {
// Break it down into smaller parts (Step 2 on the chart)
// and recursively repeat the process for the new parts (Step 3 on the chart).
return fib(num1 - 1) + fib(num1 - 2);
}
}

console.log(fib(6));

关于javascript - 简单的函数返回我在 JavaScript 中没想到的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com