Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Help with creating quadratic function program

Im trying to create a quadratic function program and I believe I have the right formula plugged in but I'm not getting the correct answer. If you can help at all let me know. Thanks. Sorry if the code gets posted unorganized.

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        double x1 = 0, x2 = 0;
        double a = 0, b = 0, c = 0, d = 0;

              System.out.println("\nThe Quadratic Formula is ax^2 + bx + c = 0. \n Please enter a: ");
       a = input.nextInt();
              System.out.println("Please enter b: ");
       b = input.nextInt();
              System.out.println("Please enter c: ");
       c = input.nextInt();

       d = Math.sqrt(Math.pow(b, 2) - 4 * a * c);

        if(d > 0)
        {
            x1 = (- b - d) / 2 * a;
            x2 = (- b + d) / 2 * a;
            System.out.println("First root is:" + x1);
            System.out.println("Second root is:" + x2);
        }
        else if(d == 0)
        {
            System.out.println("Roots are equal");
            x1 = ( - b - d) / 2 * a;
            System.out.println("Root:" + x1);
        }
        else
        {
            System.out.println("Roots are imaginary or negative");
        }
    }
}

fixed code formatting

1 Answer

Hi Timothy,

The discriminant is the part inside the square root not including the square root itself. You should only calculate b^2 - 4ac for that part.

You'll need to update the if block to calculate the square root of the variable d since it was removed from the discriminant.

Also, the quadratic formula has 2a for the denominator. You'll need to wrap all your 2 * a with parentheses. Otherwise the a will be treated as if it's in the numerator based on left to right evaluation.

Also, when d is 0 you don't have to worry about subtracting it in the formula.