In: Computer Science
You must implement a simple program that asks the user for three values, a, b, and c, which you should store as double values. Using these numbers, you compute the value of the two solutions to the quadratic equation, assuming that the equation is of the form: ax^2 + bx + c = 0
Complete the description of the program given above so that your output looks as close to the following sample output as possible. In this sample, the user entered 2, -5, and 2, respectively. User input is shown in green.
Output:
Welcome to the quadratic equation solver!
For an equation of the form ax^2 + bx + c,
Enter a: 2
Enter b: -5
Enter c: 2
The answers are x = 2.0 and x = 0.5
Need to use the quadratic formula. Have to compute the + and - parts separately, since Java does not contain a ± operator. You will need to use the Math.sqrt() method.
import java.util.Scanner; public class QuadraticEquation { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Welcome to the quadratic equation solver!"); System.out.println("For an equation of the form ax^2 + bx + c,"); System.out.print("Enter a: "); double a = in.nextDouble(); System.out.print("Enter b: "); double b = in.nextDouble(); System.out.print("Enter c: "); double c = in.nextDouble(); double d = b * b - 4 * a * c; if (a == 0 || d < 0) { System.out.println("This equation has no real roots."); } else { double r1 = (-b + Math.sqrt(d)) / (2 * a); double r2 = (-b - Math.sqrt(d)) / (2 * a); System.out.println("The answers are x = " + r1 + " and x = " + r2); } } }