Why is my arithmetic mean wrong?

1
var n1 = prompt("Nota 1: ");
alert(n1);
var n2 = prompt("Nota 2: ");
alert(n2);
var media = (n1+n2)/2;


if(media >= 6){
    alert("Aprovado!\n\nMédia: " + media);
}else{
    alert("Reprovado!\n\nMédia: " + media);
}

When done by console.log the result appears correct, but not prompt.

    
asked by anonymous 04.01.2018 / 01:12

2 answers

2

Because the prompt returns string . In case n1+n2 you are concatenating strings and not adding numbers.

The correct thing would be to convert the prompt values to type number:

var n1 = Number(prompt("Nota 1: "));
alert(n1);
var n2 = Number(prompt("Nota 2: "));
alert(n2);
var media = (n1+n2)/2;


if(media >= 6){
    alert("Aprovado!\n\nMédia: " + media);
}else{
    alert("Reprovado!\n\nMédia: " + media);
}
    
04.01.2018 / 01:27
2

This happens because window.prompt returns the value in string . Other than PHP , javascript will not add the value using only the + sign. In this case, the javascript will only concatenate the values in string and then divide by 2.

Example:

When you enter the value of 10 for n1 and n2 , with the sign of + you will be reporting to javascript concatenated these values, ie 10 concatenated with 10 is equal to 1010 , divided by 2, 505.

To work around this problem, you must convert from string to integer . For this conversion you can use parseInt or parseFloat

var n1 = parseInt(prompt("Nota 1: "));
alert(n1);
var n2 = parseInt(prompt("Nota 2: "));
alert(n2);

var media = (n1+n2)/2;

if(media >= 6){
    alert("Aprovado!\n\nMédia: " + media);
}else{
    alert("Reprovado!\n\nMédia: " + media);
}
    
04.01.2018 / 01:28