查詢二次方程的根 - JavaScript
我們需要編寫一個 JavaScript 函式,它接受三個數字(分別表示二次二次方程中的二次項係數值、一次項係數值和常數)。
而且我們還需要找出根(如果它們是實根),否則我們必須返回 false。讓我們編寫這個函式的程式碼
示例
以下為程式碼 −
const coefficients = [3, 12, 2]; const findRoots = co => { const [a, b, c] = co; const discriminant = (b * b) - 4 * a * c; if(discriminant < 0){ // the roots are non-real roots return false; }; const d = Math.sqrt(discriminant); const x1 = (d - b) / (2 * a); const x2 = ((d + b) * -1) / (2 * a); return [x1, x2]; }; console.log(findRoots(coefficients));
輸出
控制檯中的輸出 −
[ -0.17425814164944628, -3.825741858350554 ]
廣告