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);
}