Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

60
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>

7 months 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.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos