Write a Java program that prints all real solutions to the quadratic equation ax2 +bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminate b2 -4ac is negative, display a message stating that there are no real solutions?
Answers
import java.io.InputStreamReader;
import java.io.IOException;
public class Quadratic{
public static void main(String[] args) throws IOException {
System.out.println("Quadratic Equation is in the form a(x^2+bx+c=0): \n");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of a:");
double a=Double.parseDouble(br.readLine());
System.out.println("Enter the value of b:");
double b=Double.parseDouble(br.readLine());
System.out.println("Enter the value of c:");
double c=Double.parseDouble(br.readLine());
System.out.println("your quadratic equation :"+a+"x^2+"+b+"x+"+c+"=0");
Double d=(Math.pow(b,2)-(4*a*c));
double root1;
double root2;
if(d<0){
System.out.println("there are no real Number soln.");
System.exit(0);
}
if(d==0){
System.out.println("Discriminant is 0 therefore roots are equal: ");
root1=((-b)/(2*a));
System.out.println("root1:"+root1);
System.out.println("root2:"+root1);
System.exit(0);
}
if (d>0) {
System.out.println("Roots of the Quadratic-Equation");
root1=((-b)+Math.sqrt(d))/(2*a);
System.out.println("root1: "+root1);
root2=((-b)+Math.sqrt(d))/(2*a);
System.out.println("root2: "+root2);
}
}
}
//import java.io.InputStreamReader;
import java.util.Scanner;
public class Quadratic{
public static void main(String[] args) {
System.out.println("Quadratic Equation is in the form (ax^2+bx+c=0): \n");
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of a:");
double a=sc.nextDouble();
System.out.println("Enter the value of b:");
double b=sc.nextDouble();
System.out.println("Enter the value of c:");
double c=sc.nextDouble();
System.out.println("your quadratic equation :"+a+"x^2+"+b+"x+"+c+"=0");
Double d=(Math.pow(b,2)-(4*a*c));
double root1;
double root2;
if(d<0){
System.out.println("there are no real Number soln.");
System.exit(0);
}
if(d==0){
System.out.println("Discriminant is 0 therefore roots are equal: ");
root1=((-b)/(2*a));
System.out.println("root1:"+root1);
System.out.println("root2:"+root1);
System.exit(0);
}
if (d>0) {
System.out.println("Roots of the Quadratic-Equation");
root1=((-b)+Math.sqrt(d))/(2*a);
System.out.println("root1: "+root1);
root2=((-b)+Math.sqrt(d))/(2*a);
System.out.println("root2: "+root2);
}
}
}