Search code examples
javajcreator

quadratic formula java NaN?


I have to a do the quadratic formula. When I build the file it has no error, but when I run the project the output is Nan. I know that is "not a number" but I dont know how to fix it.

import java.io.*;
class cuadratica 
{
    public static void main(String [] args) throws IOException
    {
        cuadra obj=new cuadra();
        System.out.println("5.  Calcular la ecuación cuadrática (ax^2 + bx + c) ");
        obj.cal();
    }
 }

 class cuadra
 {
     void cal() throws IOException
     {
         String x;
         int a;
         String w;
         int b;
         String t;
         int c;
         int g;
         int f;
         double num3;
         double num2;
         double q;
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(isr);
         System.out.println("Inserte el primero numero (ax^2)" );
         x=br.readLine();
         a=Integer.parseInt(x);
         System.out.println("Inserte el segundo numero (bx)");
         w=br.readLine();
         b=Integer.parseInt(w);
         System.out.println("Inserte el tercer numero (c)");
         t=br.readLine();
         c=Integer.parseInt(t);
         g=(b*b)-(4*a*c);
         q=Math.sqrt(g);
         if (a!=0||g>0)
         {
             num2 = (-b+q)/(2*a);
             num3 = (-b-q)/(2*a);
             System.out.println("La raiz son "+num2+" y "+num3);
         }
         else 
         {
             System.out.println("error");
         }
     }
}

Solution

  • When solving quadratic equation ax^2 + bx + c = 0 with real coefficients, the roots of the equation will fall in one of the following categories:

    1. Two real roots
    2. Repeated real root
    3. Two complex roots

    I have tried your program, it gives correct solution for the case a = 1, b = 2, c = 1, but NaN for a = 1, b = 1, c = 1. In order to fix your logical error, you must check the discriminant b^2 - 4ac (the variable g in your code) is non-negative before you take the square root (when the discriminant is negative, it corresponds to case 3 above). Otherwise you will get NaN when taking square root of a negative number.