单击按钮以获取前 12 个斐波那契数的总和

Click button to get the sum of the first 12 Fibonacci numbers

本文关键字:按钮 获取 单击      更新时间:2023-09-26

我想获取并添加前 12 个偶数斐波那契数,并在单击按钮时将其显示在我的页面上。现在我的代码获取并添加偶数。如何将其限制为前 12 个偶数?

提前谢谢你。 http://jsfiddle.net/lakenney/oryygn4y/

    // first we get the HTML for the button
var getFibSum = document.getElementById("sumFib");
//then we set the event handler for when the button is clicked
getFibSum.onclick = function(){
               document.getElementById("sumFibResult").innerHTML = twelveEvenFibonacciSum();
 }
 /*
  *  twelveEvenFibonacciSum - calulates the sum of the first 12 even fibonacci numbers, with 0, 1 being the first two numbers of the sequence
  */
    function twelveEvenFibonacciSum(){
     /// WRITE YOUR CODE HERE
        // Loop that generates Fibonacci numbers. 
        console.clear();
        var fib = [0, 1]; //Initialize array
        var sum = 0;
        for (var i= 2; i <= 50; i++) {
            fib[i] = fib[i-1] + fib[i-2];    
            var integer = fib[i];
            if(integer  % 2 == 0) {
                 // console.log("my current even fib is " + fib[i]);
                 var sumFibResult = sum += fib[i];
                console.log("my current even fib added to sum " + sumFibResult);
            }
            // Loop until we have 12 even numbers
            }
        //console.log(fib);
       return sumFibResult;
 }

向外部作用域添加一个变量,每次调用函数时,该变量都会递增。当此值等于 12 时返回。

    for (var i= 2; i <= 50; i++) {
        fib[i] = fib[i-1] + fib[i-2];    
        var integer = fib[i];
        if(integer  % 2 == 0) {
             // console.log("my current even fib is " + fib[i]);
             var sumFibResult = sum += fib[i];
            console.log("my current even fib added to sum " + sumFibResult);
            timesIncremented++;
        }
        // Loop until we have 12 even numbers
        if(timesIncremented >= 12) {
            return;
        }
    }