Getting wrong output when trying to loop through t

2020-05-08 07:20发布

问题:

I am new to JavaScript and am having trouble getting my code to work. Any help/guidance is greatly appreciated.

I am getting the wrong output (currently “9.715575428267785e+30“) when trying to “displays the sum of first 50 even Fibonacci numbers”

I needed to: 1. create a loop that generates Fibonacci numbers. 2. test each one for whether it's even or odd. 3. Add up up the even ones, counting them as you go.

------------HERE IS MY CODE THUS FAR --------

<div id="sumFib" class="hwbutton">Get the Sum!</div>
The sum of the first 50 even Fibonacci numbers is: 
<span class="" id="sumFibResult"></span>

<script>    
    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>

http://jsfiddle.net/isherwood/38gPs

回答1:

I disagree with the people saying this is a duplicate because I think the real question you are asking is "how do I debug my failing program?" I am sure that must be a duplicate too but, well, hem...

Anyhow I think what would help you a lot here is console.log(). I don't know what browser you are using but all major ones have a JS console. (I recommend Firefox with Firebug.) Add lines like:

console.log('integer for ' + loopFib + '=' + integer);

Or

console.log('display=' + display);

To the relevant points in your script. Then open your browser's JavaScript console to view the results. I already see some major boners in your code but I'm not going to correct them for you - this is your homework assignment after all and I'd rather teach a man to fish. Comment on this reply if you have any more questions.