0

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.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Fraser Price
  • 899
  • 6
  • 15
  • 36
  • 1
    Style tip: don't spell it all out, introduce some intermediate variables. The root of the discriminant, for one thing, just begs to be calculated separately and reused. – Seva Alekseyev Dec 03 '12 at 21:33

2 Answers2

1

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)
                );
    }
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

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.

jesse reiss
  • 4,509
  • 1
  • 20
  • 19
  • ah got it ((-b + (Math.sqrt(b*b-4*a*c)))/2*a) – Fraser Price Dec 03 '12 at 21:31
  • Nope you switched /(2*a) with /2*a which is not the same thing. – Peter Lawrey Dec 03 '12 at 21:33
  • FWIW, if you have a syntax-highlighting editor, it should be able to show you matching parenthesis, which helps a bit. Better still, name some of those repeated sub-expressions as variables, and simplify the tangle of parentheses. – Useless Dec 03 '12 at 21:35