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.
What is the initial value of
num
?– Woss
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).
– Maniero