Search code examples
javaif-statementequationpolynomial-mathquadratic

Finding roots of quadratic equation using a specific class


i have this assignment that asks me to write a code that determines the roots of a quadratic equation (ax^2 + bx + c = 0). but i have to use the university's library (type.lib.Equation;).

i almost got everything figured out, except the case where there are two roots. i can get the 1st root but i'm still circling around to get the the 2nd root

my code so far

import java.util.Scanner;
import java.io.PrintStream;
import type.lib.Equation;

public class Check05A
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        PrintStream output = System.out;
        Scanner input = new Scanner(System.in);

        output.println("Enter a,b,c pressing ENTER after each... ");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        output.print("The equation: ");
        Equation x = new Equation(a, b, c);
        output.print(x);
        int root = x.getRootCount();




        if(root == 0)
        {
            output.println(" has no real roots.");
        }
        if(root == 1)
        {
            double r1 = x.getRoot(root);
            output.println(" has the single root: " + r1);
        }
        if(root == 2)
        {
            double r1 = x.getRoot(root);
            double r2 = -x.getRoot(root);
            output.println(" has the two roots: " + r2 + " and " + r1);
        }
        if(root == -1)
        {

            output.println("\nis an identity - any value is a root.");
        }









    }

}

for example 1, 2, -4 should output as :

"has the two roots: -3.23606797749979 and 1.2360679774997898"


Solution

  • You're just putting negative sign to root 1.

    This isn't always the case.

    Look up the formula for finding the roots for a quadratic equation:

    x=\frac{-b \pm \sqrt {b^2-4ac}}{2a}.
    

    and inside your function x.getRoot(), return two values inside an array.