本文介绍了一个Javascript数组中的偶数和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图将斐波那契数列的偶数相加。为什么不把所有的数字相加在一起,只用最后一个数字?我怎样才能把所有的偶数加起来?
这里是我的代码:

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

fib [0] = 0;
fib [1] = 1; (i = 2; 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);


解决方案

外循环。试试这个:

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

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


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);   
}
解决方案

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);   
}

这篇关于一个Javascript数组中的偶数和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:51