Java program to find the root of quadratic equation.


Program
import java.util.Scanner; public class QuadraticEquationProgram { public static void main(String args[]){ //Quadratic Equation - ax2 + bx + c = 0 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(); double determinant = (b*b)-(4*a*c); double sqrt = Math.sqrt(determinant); if(determinant>0){ double root_1st = (-b + sqrt)/(2*a); double root_2nd = (-b - sqrt)/(2*a); System.out.format("Root1 = %.2f and Root2 = %.2f", root_1st, root_2nd); } else if(determinant == 0) { double root = (-b + sqrt)/(2*a); System.out.format("Root is %.2f",root); } else { double real = -b / (2 * a); double imaginary = Math.sqrt(-determinant) / (2 * a); System.out.format("Root1 = %.2f+%.2fi", real, imaginary); System.out.format("\n Root2 = %.2f-%.2fi", real, imaginary); } } }
Input
Output