简体   繁体   中英

How do I add inputs together in a do while loop?

hi im very new to javascript and stuck doing my homework. My question is how do I add multiple inputs together in a do while loop? I am supposed to get all the inputs added together then divided by the amount of inputs to get the average. For example if the user were to input 7, 3, 5 and 2 then the answer will be 4.25.This is what I have so far.

var prompt;
var input = prompt("Please enter a number, input a negative number to  stop");
var number = input >= 0;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
    input = +prompt("Error enter a positive number to start");
}
do {
    input = +prompt("Enter another number, a negative to stop");
    sum += number;
    //inputs added together goes here
}     while (input >= 0);
alert(); //inputs added together divided by sum goes here

Increase the value of sum2 to count the no input. And add a condition that if the user enter a negative value then the total will be divided by the no of inputs.

I have edited your code.

var prompt;
var input = prompt("Please enter a number, input a negative number to  stop");
var number;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
number=input;
alert(number);
sum += number;
sum2++;
if(input<0){
sum +=(-number);
alert("average"+(sum/(sum2-1)));
}
//inputs added together goes here
}     while (input >= 0);
alert();

Hope it will help.

Hi try this version;

var num = 0, sum = 0, count = 0; 
do { 
num = parseInt(prompt('Enter Number')); 
sum = num >= 0 ? sum+=num : sum; 
count = num >= 0 ? count+=1: count; } 
while(num >= 0);
console.log(sum + ' count is ' + count);
console.log(sum/count);

Basically I read from prompt, convert the input to integer, I sum the numbers if they are 0 or greater. I add 1 to the count if number is 0 or greater then I divide the sum by the count

'use strict';
let input, sum = [];
do {
    input = prompt("Enter another number, a negative to stop");
    sum.push(input);
} while (input >= 0);
alert(sum.filter((a, b) => {return a + b}) / sum.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM