Given the coefficients of a quadratic equation the task is to calculate the roots of the equation if any.
Use formula:
Discriminant (d) = b2 – 4ac
If discriminant is less than 0 then no roots exist.
Roots = (-b ± √d)/2a
Java
import java.util.*;
public class QuadRoot
{
double a,b,c,r1,r2;
QuadRoot(int x,int y,int z)
{
a=x;
b=y;
c=z;
r1=0.0;
r2=0.0;
}
public void getRoots()
{
double d=(b*b)-(4*a*c);
if(d<0)
{
System.out.println("Roots are not possible");
System.exit(1);
}
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
}
public void printRoots()
{
System.out.println("Root 1: "+r1);
System.out.println("Root 2: "+r2);
}
public static void main(String args[])
{
int x=0,y=0,z=0;
Scanner sc=new Scanner(System.in);
System.out.println("Quadratic Equation General Form: Ax²+Bx+C");
System.out.print("A: ");
x=sc.nextInt();
System.out.print("B: ");
y=sc.nextInt();
System.out.print("C: ");
z=sc.nextInt();
QuadRoot ob=new QuadRoot(x,y,z);
ob.getRoots();
ob.printRoots();
}
}Java