Java Online Compiler
Example: Java Program to Find the Roots of a Quadratic Equation using sqrt() Function
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Java Program to Find the Roots of a Quadratic Equation using sqrt() Function import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); double p, q, r, d, r1, r2, rp, ip; // p, q and r - To store the real numbers // d - To store the discriminant // r1 - To store the first root // r2 - To store the second root // rp - To store the real part // ip - To store the image part System.out.println ("-----Enter the these coefficients a, b and c----"); p = in.nextFloat(); q = in.nextFloat(); r = in.nextFloat(); d = q * q - 4 * p * r; if (d > 0) { // It is the condition for real and different roots r1 = (-q + Math.sqrt(d)) / (2 * p); r2 = (-q - Math.sqrt(d)) / (2 * p); System.out.println ("\nThe r1 = " + r1 + " & r2 = " + r2); } else if (d == 0) { // It is the condition for real and equal roots r1 = r2 = -q / (2 * p); System.out.println ("\nThe r1 = r2 = " + r1 + ";"); } else { // if the roots are not real number rp = -q / (2 * p); ip = Math.sqrt(-d) / (2 * p); System.out.printf ("\nThe r1 = %.2f+%.2fi & r2 = %.2f-%.2fi\n", rp, ip, rp, ip); } } }
7.8 5.3 6.2
Output
Clear
ADVERTISEMENTS