javascript - Euler #2 Fibonacci Javascript 函数在处理数字后只会返回零

标签 javascript fibonacci

我编写了一个函数来解决 JavaScript 中的 Euler #2,将所有偶数斐波那契数相加到 4,000,000。然而,当我运行我的函数时,chrome 开发工具不断给我零作为答案。我不知道为什么。

function DoEverything() {
  oldnum = 0;
  num = 1;
  total = 0;
  result = addFibNumbers(num, oldnum);
  console.log(result);
} 
function addFibNumbers(num, oldnum) {
  while(num < 4000000) {
    if (num % 2 == 0) {
      newnum = num + oldnum;
      total += newnum;
      oldnum = num;
      num = newnum;
    }
  return total;
  }
}
DoEverything();

最佳答案

返回0的原因:

result = addFibNumbers(num, oldnum);//num=1,oldNum=0

//function
while(num < 4000000) { //num is 1, so it enters while
if (num % 2 == 0) {// 1 % 2 == 1, so skip this if
return total;// this ends the function, returning total=0 as nothing was changed

我猜你想这样做:

  while(num < 4000000) {
      newnum = num + oldnum;
      if (newnum % 2 == 0 && newnum < 4000000) {
          total += newnum;
      }
      oldnum = num;
      num = newnum;
  }
  return total;

关于javascript - Euler #2 Fibonacci Javascript 函数在处理数字后只会返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351981/

相关文章:

javascript - AngularJS延迟 View 显示

Javascript 切换按钮来更改其标题

javascript - JSON stringify 将 0 转换为 null

javascript - 将 anchor 保存在 ie6 历史记录中

c - C语言的黄金比例?

python - 在 Python 中计算斐波那契数列

javascript - Javascript 中大数的斐波那契数

javascript - jQuery 选择器中使用的函数参数

python - 斐波那契数列之和

python - 使用O(1)空间在python中自下而上的斐波那契