Math.sqrt showing an unexplained error in eclipse when trying to solve a second degree equation

104 views Asked by At

I'm trying to create a program that solves second degree equations (ax 2 + bx + c = 0). It works fine when I remove Math.sqrt(delta) but having it is a very important part of the process and I can't figure out why it doesnt work.

When I run the program it gives me X1 = Nan X2 = Nan at the end.

public static void main(String[] args) {
    double a, b, c, x1, delta;
    
    Scanner sc = new Scanner(System.in);
    System.out.println("Entrez Les Valeurs De a, b et c: ");
    a = sc.nextInt();
    b = sc.nextInt();
    c = sc.nextInt();
    
    delta = (b * b) - 4 * ( a * c );


    x1 = (-b + Math.sqrt( delta ) )/(2 * a);
    
    
    System.out.println("X1= " + x1);
                    
    
}
1

There are 1 answers

0
abe On BEST ANSWER

If delta turns out to be negative, sqrt will return NaN