javascript - 为什么我的函数将一个值推得太大?

标签 javascript fibonacci

我正在尝试编写自己的斐波那契函数。它应该返回数组中所有小于 num 的斐波那契数。我尝试使用 while 循环检查 currentPushnum ,但它会将一个值过多地插入返回的数组。

我的代码有什么问题吗?它应该在最后一次迭代之前停止,因为 currentPush 肯定大于 num

function fib(num) {

  if(num < 2){return 1};

  let fib = [1, 1];
  let currentPush = 2;

  while (currentPush < num){
    // get last two elements from array and add them together
    currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    fib.push(currentPush);
  }

  return fib;
}
 console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
 console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]

最佳答案

正如评论中提到的,您必须检查 currentPush < num在插入数组之前但在计算之后 currentPush

function fib(num) {

  if(num < 2) {return 1};

  let fib = [1, 1];
  
  while (true) {
    let currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    if (currentPush > num)
      return fib;
    fib.push(currentPush);
  }
}

console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]

关于javascript - 为什么我的函数将一个值推得太大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398947/

相关文章:

javascript - 将 Laravel 集合推送到 javascript 数组中

Javascript 确定 svg 文本是否部分或全部可见

javascript - 配置 `@babel/runtime-corejs3` 排除 es.date.now

python - 如何在 Python 中将斐波那契数列打印到第 n 个数?

Java递归斐波那契值

c - 并行化斐波那契数列生成器

javascript - jquery 和 IE8 animate opacity 解决方案

javascript - 有没有更好的方法在 Sails JS 中使用嵌套(关联)模型?

javascript - 无需任何循环/递归即可生成斐波那契数

c++ - 改进 C++ 斐波那契数列