Fraser Price
Fraser Price

Reputation: 909

Attempting to program quadratic formula?

I am new to Java - one of my first projects is to build a calculator.

Attempted to program a quadratic equation; and although I got no errors, I got the wrong answer.

void quadratic() {
    if((b*b-4*a*c) < 0){
        System.out.println("The answer is imaginary.");
    }
    else {
        System.out.println(
             "The two roots x values of the quadratic function "
             + a + "x^2 + " + b + "x + " + c + " are "
             + ((-b) + (Math.sqrt((b*b)-(4*a*c))/(2*a))) + " and "
             + ((-b) - (Math.sqrt((b*b)-(4*a*c))/(2*a)))
        );
    }
}

If I substitute a=1, b=4, c=4, I get -4 and -4.

If I substitute a=1, b=1, c=-12, I get 2.5 and -4.5.

It may just be a mathematical error, but I think the formula's correct.

Upvotes: 0

Views: 2406

Answers (2)

NPE
NPE

Reputation: 500883

No, the forumlas are not quite right. You are dividing the wrong thing by 2*a.

My advice would be to factor out the discriminant calculation, and get rid of the redundant parentheses. This will make it easier to get the code right:

void quadratic() {
    double discriminant = b*b-4*a*c;
    if(discriminant < 0) {
        System.out.println("The answer is imaginary.");
    } else {
        System.out.println(
                "The two roots x values of the quadratic function "
                + a + "x^2 + " + b + "x + " + c + " are "
                + (-b + Math.sqrt(discriminant)) / (2*a) + " and "
                + (-b - Math.sqrt(discriminant)) / (2*a)
                );
    }
}

Upvotes: 1

jesse reiss
jesse reiss

Reputation: 4579

You're missing parentheses, should be

(((-b) + (Math.sqrt((b*b)-(4*a*c)))/(2*a))) + " and " + (((-b) - (Math.sqrt((b*b)-(4*a*c)))/(2*a))))

You need to divide the whole thing by 2a.

Upvotes: 0

Related Questions