I have this code so far but every time i run and put the three numbers in a get the roots are NaN can some one please help or point me to where i went wrong.
import java.util.Scanner;
class Quadratic {
public static void main(String[] args) {
System.out.println("Enter three coefficients");
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double root1= (-b + Math.sqrt( b*b - 4*a*c ) )/ (2*a);
double root2= (-b - Math.sqrt( b*b - 4*a*c ) )/ (2*a);
System.out.println("The roots1 are: "+ root1);
System.out.println("The roots2 are: " + root2);
}
}
You have to remember that not every quadratic equation has roots that can be expressed in terms of real numbers. More specifically, if
b*b - 4*a*c < 0, then the roots will have an imaginary part andNaNwill be returned, sinceMath.sqrtof a negative number returnsNaN, as specified in the documentation. This works for coefficients such thatb*b - 4*a*c >= 0, however:If you wanted to account for non-real roots as well, you could do something like