我写了一个函数来解决Java中的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/

10-11 17:55