JavaScript(JS) JS solve quadratic equation
To solve a quadratic equation of the form ax^2 + bx + c = 0
using JavaScript, you can use the following code:
function solveQuadratic(a, b, c) { let discriminant = b * b - 4 * a * c; if (discriminant < 0) { return "No real roots"; } else if (discriminant === 0) { let root = -b / (2 * a); return `One real root: ${root}`; } else { let root1 = (-b + Math.sqrt(discriminant)) / (2 * a); let root2 = (-b - Math.sqrt(discriminant)) / (2 * a); return `Two real roots: ${root1} and ${root2}`; } } // Example usage: console.log(solveQuadratic(2, 5, 2)); // Output: Two real roots: -0.5 and -2 console.log(solveQuadratic(1, 2, 1)); // Output: One real root: -1 console.log(solveQuadratic(1, -3, 4)); // Output: No real roots
In this code, we define a function called solveQuadratic
that takes in three parameters, a
, b
, and c
, representing the coefficients of the quadratic equation.
We first calculate the discriminant using the formula b^2 - 4ac
. If the discriminant is negative, then the quadratic equation has no real roots, so we return the string "No real roots"
. If the discriminant is 0, then the quadratic equation has one real root given by the formula -b/2a
, so we calculate this root and return the string "One real root: "
followed by the value of the root. If the discriminant is positive, then the quadratic equation has two real roots given by the formulas (-b + sqrt(discriminant))/2a
and (-b - sqrt(discriminant))/2a
, so we calculate these roots and return the string "Two real roots: "
followed by the values of the roots.
To use the function, you can call it with the desired coefficients as shown in the example usage. This will print the number of real roots and the values of the roots to the console, depending on the coefficients.