Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda