Write a method called quadratic that solves quadratic equations and prints their roots. Recall that a quadratic equation is a polynomial equation in terms of a variable x of the form ax2 bx c 0. The formula for solving a quadratic equation is:
Here are some example equations and their roots:
x2-7x+12:x=4,x=3
x2+3x+2:x=-2,x=-1
Your method should accept the coefficients a, b, and c as parameters and should print the roots of the equation. You
may assume that the equation has two real roots, though mathematically this is not always the case.
Program:
public class Ch03Ex08
{
public static void main(String[] args)
{
quadratic(1, -7, 12);
quadratic(1, 3, 2);
}
public static void quadratic(int a, int b, int c)
{
double r1 = (-1 * b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
double r2 = (-1 * b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
System.out.println("x=" + r1 + ", x=" + r2);
}
}
Output:
x=4.0, x=3.0
x=-1.0, x=-2.0