Javascript循环通过Fibonacci数字并测试偶数

时间:2014-03-07 02:34:27

标签: javascript arrays loops if-statement

我试图“显示前50个甚至斐波纳契数字的总和”,目前输出错误。

我需要:

  1. 创建一个生成斐波那契数字的循环。

  2. 测试每一个是偶数还是奇数。

  3. 添加偶数,计算它们。

  4. 我是JavaScript的新手,无法让我的代码工作。非常感谢任何帮助/指导。他们是一个更好,更简单的方式吗?

    ------------这是我的代码,因为--------

    <div id="sumFib" class="hwbutton">Get the Sum!</div><br>
    
    The sum of the first 50 even Fibonacci numbers is: <span class="" id="sumFibResult"></span>
    <br>
    
    <script type="text/javascript">
    var getFibSum = document.getElementById("sumFib");
    getFibSum.onclick = function(){
    fiftyEvenFibonacciSum();
     }
    
    function fiftyEvenFibonacciSum(){
    
    var loopFib;
    
    //Initialize fibonacci array
    
    var fibonacci = new Array();
    
    //Add fibonacci array items
    fibonacci[0] = 0;
    fibonacci[1] = 1;
    var sum=0;
    
    //Since it takes 150 fib numbers to obtain 50 even, loop through that many.
    for(loopFib=2; loopFib<=150; loopFib++) {
    
        // Next fibonacci number = previous + one before previous
        fibonacci[loopFib] = fibonacci[loopFib-2] + fibonacci[loopFib-1];
    
        //test for even numbers with if then statement
        var integer = parseInt(fibonacci[loopFib]);
    
        if (integer % 2 == 0) {
    
        //Add up the even fib numbers if even and output into dispay variable
        var display = sum += fibonacci[loopFib];
    
        //output results to html page
        document.getElementById("sumFibResult").innerHTML = display ;
    
    }
    }
    }
    </script>
    

2 个答案:

答案 0 :(得分:0)

试试这个我添加了一个计数器来阻止在达到50之后添加偶数的执行,让我知道是否有效

    var fibonacci = new Array();

//Add fibonacci array items
fibonacci[0] = 0;
fibonacci[1] = 1;
var sum=0;

//Since it takes 150 fib numbers to obtain 50 even, loop through that many.
var counter=0;
for(loopFib=2; loopFib<=150; loopFib++) {

    // Next fibonacci number = previous + one before previous
    fibonacci[loopFib] = fibonacci[loopFib-2] + fibonacci[loopFib-1];

    //test for even numbers with if then statement
    var integer = parseInt(fibonacci[loopFib]);

    if (integer % 2 == 0  && counter < 50) {
        counter++;
        //Add up the even fib numbers if even and output into dispay variable
        var display = sum += fibonacci[loopFib];
    //console.log(fibonacci[loopFib]);   //output results to html page
            //console.log(counter);  
        document.getElementById("sumFibResult").innerHTML = display ;

}
}

答案 1 :(得分:0)

这就是我的做法。

let num = 1;
let sum = 0;
let counter = 0;

function evenCheck(x)
{
    if(x%2===0)
    {
        return true;
    }
return false;
}

for(let i=0; i<1000; i+=num)
{
    num += i;
    if(counter>=50)
    {
        break;
    }
    if(evenCheck(i))
    {
        sum += i;
        counter++;
    }
    if(evenCheck(num))
    {
        sum += num;
        counter++;
    }
}
console.log(sum);