why does NaN give me?

1

I'm trying to perform a quadratic function and it returns NaN Can you help me please?

var a= parseInt(prompt());
var b= parseInt(prompt());
var c= parseInt(prompt());
var d=Math.sqrt(b-4*a*c);
var e=d-b;
e=e/(2*a);
document.write("<p>"+e+"</p>");
var f = d*-1;
e=f-b;
e=e/(2*a);
document.write("<p>"+e+"</p>");
    
asked by Jose Francisco Murga 15.11.2017 в 15:58
source

2 answers

6

Okay, the problem you have is the numbers you are entering.

var d=Math.sqrt(b-4*a*c);

Calculate the square root, but remember that if b-4*a*c is negative , then is indeterminate.

You must validate that b > (4*a*c) or b-4*a*c >= 0

so you can see what I say, try to connect these values.

var a= parseInt(1);
var b= parseInt(20);
var c= parseInt(2);
var total_raiz = b-4*a*c;
if(total_raiz < 0){
 console.log("No es posible encontrar la raíz cuadrada de un número negativo");
}else{
 var d=Math.sqrt(total_raiz);
 var e=d-b;
 e=e/(2*a);
 document.write("<p>"+e+"</p>");
 var f = d*-1;
 e=f-b;
 e=e/(2*a);
 document.write("<p>"+e+"</p>");
}
    
answered by 15.11.2017 / 16:06
source
2

You can not get the square root of a negative number, the variable b must be greater than 4 * a * c then validate in the code before performing the operation

 var a= parseInt(prompt());
var b= parseInt(prompt());
var c= parseInt(prompt());
if(b < (4*a*c)){
 document.write("No se pueden obtener raices reales");
}else{

  var d=Math.sqrt(b-4*a*c);
  var e=d-b;
  e=e/(2*a);
  document.write("<p>"+e+"</p>");
  var f = d*-1;
  e=f-b;
  e=e/(2*a);
  document.write("<p>"+e+"</p>");

}
    
answered by 15.11.2017 в 16:10