Write a program in Java to find and print all the roots of quadratic equation

  


Write a program in JAVA to find and print all the roots of quadratic equation

import java.util.Scanner;

public class QuadEq {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a, b, c, val1, val2;
System.out.print("Enter The value of a in ax^2+bx+c : ");
a = sc.nextDouble();
System.out.print("Enter The value of b in ax^2+bx+c : ");
b = sc.nextDouble();
System.out.print("Enter The value of c in ax^2+bx+c : ");
c = sc.nextDouble();
sc.close();
double dis = Math.pow(b, 2) - 4 * a * c;
if (dis == 0) {
val1 = (-b) / (2 * a);
System.out.print("Roots are Real & Equal. X1 = x2 = : " + val1);
} else if (dis > 0) {
val1 = (-b + Math.sqrt(dis)) / (2 * a);
val2 = (-b - Math.sqrt(dis)) / (2 * a);
System.out.print("Roots are Real & Different. X1 = : " + val1 + " & X2 = " + val2);
} else {
val1 = -b / (2 * a);
val2 = (Math.sqrt(-dis)) / (2 * a);
System.out.println("Roots are Complex & Different.");
System.out.println("X1 = " + val1 + " + " + val2 + "i" + "\nX2 = " + val1 + " - " + val2 + "i");
}

}
}

OUTPUT

Enter The value of a in ax^2+bx+c : 1
Enter The value of b in ax^2+bx+c : -4
Enter The value of c in ax^2+bx+c : 6.25
Roots are Complex & Different.
X1 = 2.0 + 1.5i
X2 = 2.0 - 1.5i
Share:

0 Comments:

Post a Comment

Pageviews