write a javascript program to find roots of quadratic equation

Solutions on MaxInterview for write a javascript program to find roots of quadratic equation by the best coders in the world

showing results for - "write a javascript program to find roots of quadratic equation "
Kurtis
28 Mar 2018
1// program to solve quadratic equation
2let root1, root2;
3
4// take input from the user
5let a = prompt("Enter the first number: ");
6let b = prompt("Enter the second number: ");
7let c = prompt("Enter the third number: ");
8
9// calculate discriminant
10let discriminant = b * b - 4 * a * c;
11
12// condition for real and different roots
13if (discriminant > 0) {
14    root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
15    root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
16
17    // result
18    console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
19}
20
21// condition for real and equal roots
22else if (discriminant == 0) {
23    root1 = root2 = -b / (2 * a);
24
25    // result
26    console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
27}
28
29// if roots are not real
30else {
31    let realPart = (-b / (2 * a)).toFixed(2);
32    let imagPart = (Math.sqrt(-discriminant) / (2 * a)).toFixed(2);
33
34    // result
35    console.log(
36    `The roots of quadratic equation are ${realPart} + ${imagPart}i and ${realPart} - ${imagPart}i`
37  );
38}