二次方程的标准形式是
ax2 + bx + c = 0
在这里,a、b和c是实数,且a不能等于0。
我们可以使用以下公式来计算二次方程的根
x = (-b ± √(b2-4ac)) / (2a)
±
符号表示将有两个根
root1 = (-b + √(b2-4ac)) / (2a)
root1 = (-b - √(b2-4ac)) / (2a)
术语b2-4ac
被称为二次方程的判别式。它决定了根的性质。即:
- 如果判别式 > 0,则根是实数且不同
- 如果判别式 == 0,则根是实数且相等
- 如果判别式 < 0,则根是复数且不同
示例:Java程序查找二次方程的根
public class Main {
public static void main(String[] args) {
// value a, b, and c
double a = 2.3, b = 4, c = 5.6;
double root1, root2;
// calculate the discriminant (b2 - 4ac)
double discriminant = b * b - 4 * a * c;
// check if discriminant is greater than 0
if (discriminant > 0) {
// two real and distinct roots
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
}
// check if discriminant is equal to 0
else if (discriminant == 0) {
// two real and equal roots
// discriminant is equal to 0
// so -b + 0 == -b
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
}
// if discriminant is less than zero
else {
// roots are complex number and distinct
double real = -b / (2 * a);
double imaginary = Math.sqrt(-discriminant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
}
}
}
输出
root1 = -0.87+1.30i and root2 = -0.87-1.30i
在上面的程序中,系数a、b和c分别设置为2.3、4和5.6。然后,discriminant
计算为b2
- 4ac
。
根据判别式的值,根的计算方式如上公式所示。请注意,我们使用了库函数Math.sqrt()来计算数字的平方根。
我们使用format()
方法打印计算出的根。
format()
函数也可以替换为printf()
,如下所示:
System.out.printf("root1 = root2 = %.2f;", root1);