该程序在已知二次方程系数时计算其根。
二次方程的标准形式是
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
为了找到这样的方程的根,我们使用以下公式:
(root1,root2) = (-b ± √b2-4ac)/2
术语 b2-4ac
被称为二次方程的判别式。它决定了根的性质。
- 如果判别式大于0,则根是实数且不同。
- 如果判别式等于0,则根是实数且相等。
- 如果判别式小于0,则根是复数且不同。

示例:二次方程的根
// program to solve quadratic equation
let root1, root2;
// take input from the user
let a = prompt("Enter the first number: ");
let b = prompt("Enter the second number: ");
let c = prompt("Enter the third number: ");
// calculate discriminant
let discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// result
console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
// result
console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}
// if roots are not real
else {
let realPart = (-b / (2 * a)).toFixed(2);
let imagPart = (Math.sqrt(-discriminant) / (2 * a)).toFixed(2);
// result
console.log(
`The roots of quadratic equation are ${realPart} + ${imagPart}i and ${realPart} - ${imagPart}i`
);
}
输出 1
Enter the first number: 1 Enter the second number: 6 Enter the third number: 5 The roots of quadratic equation are -1 and -5
上述输入值满足第一个 if
条件。这里,判别式将大于0,并执行相应的代码。
输出 2
Enter the first number: 1 Enter the second number: -6 Enter the third number: 9 The roots of quadratic equation are 3 and 3
上述输入值满足 else if
条件。这里,判别式将等于0,并执行相应的代码。
输出 3
Enter the first number: 1 Enter the second number: -3 Enter the third number: 10 The roots of quadratic equation are 1.50 + 2.78i and 1.50 - 2.78i
在上面的输出中,判别式将小于0,并执行相应的代码。
在上面的程序中,使用 Math.sqrt()
方法来查找数字的平方根。您可以看到程序中也使用了 toFixed(2)
。这会将小数四舍五入到两位小数。
上面的程序使用了 if...else
语句。如果您想了解更多关于 if...else
语句的信息,请访问 JavaScript if...else Statement。