-1

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
T.Trinh
  • 23
  • 4
  • You don't need the first input, nor the while loop. `prompt` and alert are already defined in client-side JS. `sum2` is unused, indentation is bad. Barring all the code comment, the algorithm is dead simple and would have been translated to JS even easier. – DrakaSAN Oct 04 '16 at 09:56
  • This question show no effort, and I hope your teacher will see it and recognize you so that he can know you need additional tutoring. – DrakaSAN Oct 04 '16 at 09:57

3 Answers3

0

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.

Pirate
  • 2,886
  • 4
  • 24
  • 42
0

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

Laazo
  • 467
  • 8
  • 22
0
'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);
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94