簡體   English   中英

我沒有弄明白我的JavaScript代碼有什么問題

[英]I don't get what's wrong with my Javascript code

我正在嘗試解決Euler項目的第二個問題:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

這就是我嘗試用Javascript解決的方式+為什么我認為這是合乎邏輯的:

var max = 4000000; //We create a variable with the maximum amount allowed, which is 4 million.
var result = 0; //Here we create a variable to store our result.

for (var i = 0; i < max; i++) //Now let's loop through the 4 million.
{
    if (i % 2 === 0) //We're checking for even numbers here because as I understood it, we have to only use the even numbers in this problem.
    {
        result = result + i; //Here we're adding "result" (Which is 0) to itself plus *i* (Which we're looping through!). We should have the result at the end of this loop.
    }
}

console.log(result); //Print our result.

我知道斐波那契數字會將行中的前一個數字加到自己,所以1 + 2將為3。

根據我的邏輯,這就是我對result = result + i所做的事情,但是我得到了錯誤的答案。

我在這里看不到邏輯。

並非每個低於4,000,000的偶數都在斐波那契數列中。 請嘗試以下操作:

var max = 4000000, first = 1, second = 1, next = 0, result = 0;
while (second < max) {      // until we pass our limit
  next = first + second;    // find the next number in the fibonacci sequence by adding the previous two
  first = second;           // move on to the next numbers in the sequence
  second = next;
  if (second % 2 === 0)     // if the second number is even
    result += second;       // add it to our result
}
return result;              // result holds the sum of all the even fibonacci numbers below our limit!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM