我正在阅读 Robert Sedgewick 和 Kevin Wayne 合着的编程入门书籍。
在其中一个例子中,他们实现了一个二次类,如下所示:
public class Quadratic
{
public static void main(String[] args)
{
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
double discriminant = b * b - 4.0 * c;
double d = Math.sqrt(discriminant);
System.out.println((-b + d) / 2.0);
System.out.println((-b - d) / 2.0);
}
}
作者省略了二次公式的'a'系数。这是因为可以抵消“a”系数(分子/分母)吗?
根据反馈……以下是否是正确的解决方案:
public static void main(String[] args)
{
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
double a = Double.parseDouble(args[2]);
double discriminant = b * b - 4.0 * a * c;
double d = Math.sqrt(discriminant);
System.out.println((-b + d) / (2.0 * a));
System.out.println((-b - d) / (2.0 * a));
}
最佳答案
不,作者可能以不同的方式实现了该算法。假设一般情况下,a
不能被取消,因为 -b
因素不包含 a。
求二次方程根的公式是:-
roots = (-b +(-) sqrt((b^2) - (4*a*c))) / (2*a).
// here - alongwith + represents how to find second root.
我建议你通过常用的方式。如果作者使用了不同的约定,请不要遵循。
请遵循标准/通用方式。这很容易理解。
Based on the feedback… Would the following be the correct solution:..
您作为编辑添加到问题中的解决方案似乎是正确的。所以,我建议你走那条路。
关于java - 实现二次算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35874045/