create a function that solves the quadratic equation in javascript

You can create a function in JavaScript that solves the quadratic equation using the following code:

index.tsx
function solveQuadraticEquation(a, b, c) {
  let discriminant = Math.pow(b, 2) - 4 * a * c;
  
  if (discriminant < 0) {
    return "No real roots";
  } else if (discriminant === 0) {
    let root = -b / (2 * a);
    return `The equation has a double root at x = ${root}`;
  } else {
    let root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
    let root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
    return `The equation has two roots: x1 = ${root1} and x2 = ${root2}`;
  }
}

// Example usage
console.log(solveQuadraticEquation(1, -5, 6));  // The equation has two roots: x1 = 3 and x2 = 2
console.log(solveQuadraticEquation(1, -2, 1));  // The equation has a double root at x = 1
console.log(solveQuadraticEquation(1, 2, 3));   // No real roots
751 chars
20 lines

In this function, a, b, and c are the coefficients of the quadratic equation in the form ax^2 + bx + c = 0. The function calculates the discriminant to determine the type and number of roots the quadratic equation has. It then returns a string indicating the nature of the roots.

related categories

gistlibby LogSnag