当二次方程的系数已知时,该程序计算二次方程的根。
二次方程的标准形式是:
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
为了找到这个方程的根,我们使用公式,
(root1,root2) = (-b ± √b2-4ac)/2
术语
如果判别式大于0,则根是实数和不同。
如果判别式等于0,则根是实数且相等。
如果判别式小于0,则根复杂且不同。
b2-4ac
被称为二次方程的判别式。它讲述了根的本质。
示例: 二次方程的根
// 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 语句。 >