0

I am trying to make an average calculator. This is my code for it:

var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
   var newdata = prompt("Enter a piece of data (must be a number)");
   data.push(newdata);
   var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
   while (i < data.length) {
      total += data[i];
      i++;
   }
}
var average = total / data.length;
document.write(average);

It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.

Coder66
  • 67
  • 8

2 Answers2

3

You need to take a number, not a string value from the prompt.

The easiest was is to take an unary plus + for converting a number as string to a number

data.push(+newdata);
//        ^

Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

vizsatiz
  • 1,933
  • 1
  • 17
  • 36