我是 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。
这可能只是一个数学错误,但我认为公式是正确的。
最佳答案
不,论坛不太正确。您除以 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)
);
}
}
关于java - 尝试编写二次公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13691898/