Search code examples
javascriptaverage

Javascript find average from user's input


I know there are similar questions on here to mine but I don't see the answer there.

Where am I going wrong with this JS code to find the average number from the user's input? I want to keep entering numbers until -1 is entered. I think -1 is being counted as an input/

    var count = 0;
    var input;
    var sum = 0;

        while(input != -1){
            input = parseInt(prompt("Enter a number"));
            count++;
            sum = sum + input;
            sum = parseInt(sum);
            average = parseFloat(sum/count);
        }

    alert("Average number is " + average);

Solution

  • This is the right order (without all the unnecessary parsing...)

    var count = 0;
    var input;
    var sum = 0;
    input = parseInt(prompt("Enter a number"));
    while (input != -1) {
    
        count++;
        sum += input;
        average = sum / count;
        input = parseInt(prompt("Enter a number"));
    }
    
    alert("Average number is " + average);    
    

    DEMO

    Note that you can calculate the average once outside of the loop and save some CPU.