2

So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".

  function Media()
 {
     var n = prompt("number of elements?");
     var i = 1;
     var s = 0;
     
     for (i=1;i<=n;i++)
     {
         var m = prompt("insert # " +i);
         s = s+m;
     }
     var media = s/n;
     document.getElementById("rezultat").innerHTML = "result: " +media
 }

I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong

0stone0
  • 34,288
  • 4
  • 39
  • 64

2 Answers2

4

You should parse the result of prompt to an integer;

How to convert a string to an integer in JavaScript?

 function Media() {
     var n = parseInt(prompt("number of elements?"));
     var i = 1;
     var s = 0;
     
     for (i=1;i<=n;i++)
     {
         var m = prompt("insert # " +i);
         m = parseInt(m);
         s = s+m;
     }
     var media = s/n;
     document.getElementById("rezultat").innerHTML = "result: " +media
 }
 
 Media();
<div id='rezultat' />
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 2
    To expand a little on why this is important, your code was doing `"1" + "2" = "12"` then `"12" / 2 = 6` due to JS's use of `+` for string concatenation (In the first sum), and automatic type conversion (In the second). – DBS Nov 24 '20 at 15:23
  • If you want that your code works also with float numbers, it is better to use "m = parseFloat(m)" in your code. – hamid-davodi Nov 24 '20 at 16:16
0

You should also parse the result of prompt using parseInt

var m = parseInt(prompt("insert # " + i));

s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.

PIG208
  • 2,060
  • 2
  • 10
  • 25