Unexpected value when averaging two numbers

Asked

Viewed 39 times

-1

var alunos = document.querySelectorAll(".aluno");

for (var registro = 0; registro<alunos.length; registro++) {

  var aluno= alunos[registro];

  var nota1 = aluno.querySelector(".info-nota1").textContent;

  var nota2 = aluno.querySelector(".info-nota2").textContent;

  var tdMedia = aluno.querySelector(".info-media");
  var media = (nota1+nota2)/2;

  aluno.querySelector(".info-media").textContent=media;

}

inserir a descrição da imagem aqui

1 answer

0

When you do Nota1 + nota2, you are concatenating these variables, rather than summing them. To solve, just use the parseint()

var alunos = document.querySelectorAll(".aluno");
for (var registro = 0; registro<alunos.length; registro++) {
  var aluno= alunos[registro];    
  var nota1 = aluno.querySelector(".info-nota1").textContent;    
  var nota2 = aluno.querySelector(".info-nota2").textContent;    
  var tdMedia = aluno.querySelector(".info-media");
  nota1 = parseInt(nota1);
  nota2 = parseInt(nota2);
  var media = (nota1+nota2)/2;    
  aluno.querySelector(".info-media").textContent=media;    
}
  • To think about: using parseInt direct on sum, the variables nota1 and nota2 evening strings for the rest of the program. It makes sense to have notes like string in that case?

  • Gee, I would never think of it ;-;. has how to do the direct sum without putting parseint?

  • I fixed the code, I had done it wrong on the fly. And @Andersoncarloswoss this is a great point to think about.

Browser other questions tagged

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