Why is the average score always "Nan"?

Asked

Viewed 154 times

0

I have a problem calculating the average of several notes typed by the user.

The function returns only Nan.

function calcularMedia() {

  var nota = parseInt(prompt("Digite uma nota:"));

  for (;;) {
    var soma = nota + soma;
    var num = num + 1;
    var dec = parseInt(prompt("Deseja continuar? Digite 1 para 'SIM' ou 2 para 'NÃO':"));

    if (dec == 2) {
      var media = parseInt((soma / num));
      alert('A média das notas digitadas é: ' + media);
      break;
    } else {
      calcularMedia();
    }
  }
}

calcularMedia();

  • What is the initial value of num?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

1

The code is very confusing. First you need to declare the variables that accumulate and count for the loop, and it would be good to initialize with 0 to make more explicit that this is the intention.

Plus you’re asking for the note out of the loop, so just ask once and it doesn’t make sense.

Calling the function again if you want to continue is not suitable and will burst the stack at some point if you have a lot of data to be typed. It will not give problem in the exercise, but why learn to do wrong?

I fixed these things and solved, but I’m still not treating a possible error if the person type something valid, the correct thing is to take care of it in the code.

<!DOCTYPE HTML>
<html>
  <head>
    <title>Exercício 2</title>
    <meta charset="utf-8" />
    <script>
    function calcularMedia() {
        var soma = 0;
        var contador = 0;
        for(;;) {
            var nota = parseInt(prompt("Digite uma nota:"));
            soma += nota;
            contador++;
            var dec = parseInt(prompt("Deseja continuar? Digite 1 para 'SIM' ou 2 para 'NÃO':"));
            if (dec == 2) {
                alert('A média das notas digitadas é: ' + parseInt(soma / contador));
                break;
            }
        }
    }
    </script>
  </head>
  <body>
  <script>calcularMedia();</script>
  </body>
</html>

I put in the Github for future reference.

His original code was this so I left like this.

0

The Nan error means "not a number", that is, somewhere in your code is not being identified a number.

Example:

parseInt('ab') vai dar NaN
parseInt('1') vai dar 1

Browser other questions tagged

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