Instantly share code, notes, and snippets.

Embed
What would you like to do?
CSC-111 In class Quadratic Equation Expression Solver
// Prof. A.C. Silvestri
// 10/13/18
// CSC-111 Intro to Java
// silvestri@stcc.edu
// Program to calculate roots of a quadratic
package chapter3;
import java.util.Scanner;
public class QuadraticEquationSolver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Quadratic Equation Solver!");
System.out.print("Enter a: ");
double a = input.nextDouble();
if (a == 0) {
System.out.println("Sorry. a cannot be 0");
}
else {
// Now enter your code here to calculate the solutions
// provided the input values represent a valid quadratic
// Remember there can be 0, 1, or 2 solutions.
// Out results accordingly.
System.out.print("Enter b: ");
double b = input.nextDouble();
System.out.print("Enter c: ");
double c = input.nextDouble();
double sqrtExpr = b*b - 4 * a * c;
if (sqrtExpr < 0) {
System.out.println("There are 0 real roots.");
}
else if (sqrtExpr == 0) {
double root = -b / (2 * a);
System.out.printf("There is 1 root: %.2f\n", root);
}
else {
double r1 = (-b + Math.sqrt(sqrtExpr)) / (2 * a);
double r2 = (-b - Math.sqrt(sqrtExpr)) / (2 * a);
System.out.printf("There are 2 roots: %.2f and %.2f\n", r1, r2);
}
}
input.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment