0

我是 Java 新手——我的第一个项目是构建一个计算器。

试图编写一个二次方程;虽然我没有错误,但我得到了错误的答案。

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)))
        );
    }
}

如果我替换a=1, b=4, c=4,我得到 -4 和 -4。

如果我替换a=1, b=1, c=-12,我得到 2.5 和 -4.5。

这可能只是一个数学错误,但我认为这个公式是正确的。

4

2 回答 2

1

不,论坛不太正确。你把错误的东西除以2*a

我的建议是排除判别式计算,并去掉多余的括号。这将使代码更容易正确:

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)
                );
    }
}
于 2012-12-03T21:37:07.700 回答
0

你缺少括号,应该是

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

您需要将整个事物除以 2a。

于 2012-12-03T21:22:44.573 回答