Pregunta

Trying to sum the even numbers of the fibonacci sequence. Why is it not summing all of the numbers together and just using the last number? How can I sum all of the even numbers together? Here's my code:

function fibonacciSum(){
    var i;
    var fib = new Array ();

    fib[0] = 0;  
    fib[1] = 1; 
        for(i=2; i<=10; i++){  
            fib[i] = fib[i-2] + fib[i-1]; 
            var number = parseInt(fib[i]);   
            var sum = 0;  
            if (number % 2 == 0) {  
                var result = sum += fib[i];  
                }  
         }  
    console.log(result);   
}
¿Fue útil?

Solución 2

You should declare sum and result outside for loop. Try this:

function fibonacciSum(){
    var i;
    var fib = new Array ();

    fib[0] = 0;  
    fib[1] = 1;
    var sum = 0; 
    var result = 0; 
    for(i=2; i<=10; i++){  
        fib[i] = fib[i-2] + fib[i-1]; 
        var number = fib[i]; 
        if (number % 2 == 0) {  
            result = sum += fib[i];  
        }  
     }  
    console.log(result);   
}

Otros consejos

var sum = 0;

This is in your loop resetting the sum on every iteration. It has to be outside the loop.

In your solution, each run of the for loop resets "sum" with the line: var sum = 0;. Set it to 0 outside the loop.

function fibonacciSum(){
    var i;
    var fib = new Array ();
    fib[0] = 0;  
    fib[1] = 1; 
    var sum = 0;
        for(i=2; i<=10; i++){  
            fib[i] = fib[i-2] + fib[i-1]; 
                var number = parseInt(fib[i]);    
                if (number % 2 == 0) {  
                    var result = sum += fib[i];  
                }  
         }  
    console.log(result);   
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top