解决二次方程式的Javascript程序
在这个例子中,您将学习编写一个程序来解决JavaScript中的二次方程式。
当已知二次方程的系数时,该程序将计算二次方程的根。
二次方程的标准形式为:
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
要找到此类方程式的根,我们使用公式,
(root1,root2) = (-b √b2-4ac)/2
术语b 2 -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语句。
上一篇: 用于检查素数的JavaScript程序
下一篇: 生成随机数的Javascript程序
总计 0 评论