There are several problems in the code, but the main one is that it is not converting a text to number. Whenever using a function you should read all of its documentation in detail and learn how to use it. A prompt()
says he will return a string, so you can’t account for it. You must use parseFloat()
in this case to convert to a number that can be calculated. Note that this conversion can give error and break the application if something is typed that cannot be converted, and this needs to be handled, this gets from exercise to you.
I used more significant variable names, simplified the calculation and eliminated unnecessary variables, and reduced their scope. I left the function because it may have a purpose, but in the current code it is simpler to do the account than to create a function. I did not use a array because everything that is not necessary only creates potential problems. It would be useful in another context, in this is only complication, the result is the same without it. The statement does not speak in array or something that implies your need.
function calcMedia(a, b) {
return (a + b) / 2;
}
var numAlunos = parseFloat(prompt("Quanto alunos você deseja verficar? "));
for (var i = 0; i < numAlunos; i++) {
var aluno = prompt("Qual o seu nome? ");
var nota1 = parseFloat(prompt("Digite sua 1ª nota: "));
var nota2 = parseFloat(prompt("Digite sua 2ª nota: "));
console.log(aluno);
console.log(nota1);
console.log(nota2);
console.log(calcMedia(nota1, nota2));
console.log("");
}
I put in the Github for future reference.
Placed ;
and stated the variables explicitly. You are in the dangerous way of trying to make the code work without understanding what is in it, of how it really should be written.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero