Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
JavaScript Quadratic Formula Equation producing NaN

I am making a quadratic formula calculator. There are no errors but when I run it it returns NaN. I do not understand why.

function quadratic(a, b, c) {    
  a = document.getElementById("a").value;
  b = document.getElementById("b").value;
  c = document.getElementById("c").value;

  var equation = Math.sqrt((b * b) - ( 4 * a * c));
  var quadraticPos =(-b + equation) / (2 * a); 
  var quadraticNeg = (-b - equation) / (2 * a);

  if (isNaN(a) || isNaN(b) || isNaN(c)) {
    alert("Invalid Input");
  } else {
    document.getElementById("quadraticOut").innerHTML =
      "Quadratic Equation = " + quadraticPos.toFixed(2) +
      "<br/>" + quadraticNeg.toFixed(2);
  }
}
input { width: 20px }
<input id="a" placeholder="a"/>
<input id="b" placeholder="b"/>
<input id="c" placeholder="c"/>
<button onclick="quadratic()">compute</button>
<div id="quadraticOut">result…</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. The input check should come before the actual calculation.

  2. a, b and c are by default strings, not numbers, when they come from the input fields through .value. They should be converted to Number() before being used in calculation. Or, you could multiply by a number, but that's a hack. If b*b multiplies two strings, the product will be a number because of type coercion, but this isn't solid and you should not rely on JavaScript oddities like this to make your calculation work.

  3. Math.sqrt() returns NaN if the result is a negative number, which is very likely to get with random input values here.

  4. Your <br/>in the innerHTML will cause an error, you need to put quotes around it.

  5. In 2021 it would be better to use let and/or const in order to limit the variable scope, instead of the global var.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda