Why is my arithmetic mean wrong?

Asked

Viewed 57 times

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 I do it by console.log the result is correct, but by prompt it is not.

  • 3

    console.log in place of prompt? How would that be? Indeed, the return of prompt always is a string. Think about it.

2 answers

2

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

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

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

2

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

Example:

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

To solve this problem, you must convert from string for integer. For this conversion you can use the 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.