一元二次方程是許多人學生時代的共同記憶。本文分享一個用 HTML 與 JavaScript 打造的在線計算器,只要輸入方程式的係數,就能自動算出兩個解(包含實數與複數解)。
計算器透過表單讓使用者輸入 a、b、c 三個係數,並提供「解題」與「重置」按鈕:
<form name="fquad">
<input size="4" name="fa" type="text"> x<sup>2</sup>+
<input size="4" name="fb" type="text"> x +
<input size="4" name="fc" type="text"> = 0
<input onclick="checkQuad()" type="button" value="解題">
<input type="reset" value="重置">
</form>
核心的計算邏輯是根據判別式(discriminant,即 b² - 4ac)的正負來決定解的形式:
function quad() {
var a = document.fquad.fa.value;
var b = document.fquad.fb.value;
var c = document.fquad.fc.value;
det = Math.pow(b,2) - 4 * a * c;
rootpart = Math.sqrt(det) / (2 * a);
rootparti = (Math.sqrt(-det) / (2 * a)) + i;
// ...
if (det == 0) {
x1 = x2 = -b / (2 * a);
} else if (det > 0) {
x1 = (-b + Math.sqrt(det)) / (2 * a);
x2 = (-b - Math.sqrt(det)) / (2 * a);
} else if ((-b / (2 * a)) == 0) {
x1 = rootparti1;
x2 = rootparti2;
} else {
x1 = (-b / (2 * a) + " + " + rootparti1);
x2 = (-b / (2 * a) + " + " + rootparti2);
}
document.fquad.x1.value=x1;
document.fquad.x2.value=x2;
}
判別式 = 0:方程式有兩個相同的實數解(重根)。
判別式 > 0:方程式有兩個相異的實數解。
判別式 < 0:方程式沒有實數解,此時程式會計算並顯示共軛複數解(透過 Math.sqrt(-det) 取得虛部)。
程式也貼心地處理了當 a 為 0 的狀況——這時方程式其實已退化成一次方程式,程式會直接算出 x = -c/b 並提示「這不是二次方程式」。
把這段程式碼存成 .html 檔案用瀏覽器打開,就能立即擁有一個隨時可用的線上方程解題小工具。