Java – what did I do wrong with this quadratic formula?

a = 1,b = -7,c = 12
a = 1,b = -7,c = 12

    public static void quadratic(double a,double b,double c){
    double r1;
    double r2;
    double turducken;
    turducken = Math.pow(b,2)-(4*a*c);
    r1 = (-1*b) + ((Math.sqrt(turducken))/(2*a));
    r2 = (-1*b) - ((Math.sqrt(turducken))/(2*a));

    System.out.println("r1: "+r1);
    System.out.println("r2: "+r2);

When the correct answer should be 4 and 3, the system prints out 7.5 and 6.5

I can't figure out what I did wrong here

Solution

should:

r1 = ((-1*b) + Math.sqrt(turducken))/(2*a);
 r2 = ((-1*b) - Math.sqrt(turducken))/(2*a);

(i.e. everything divided by 2 * a)

You can further simplify your expression:

double sq = Math.sqrt(b*b - 4*a*c);
 r1 = (-b + sq)/(2*a);
 r2 = (-b - sq)/(2*a);

I find that the simpler the expression, the easier it is to find mistakes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>