In this example, you will learn to write a program that solves a quadratic equation in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
- JavaScript if...else Statement
- JavaScript Math sqrt()
This program computes roots of a quadratic equation when its coefficients are known.
The standard form of a quadratic equation is:
ax2 + bx + c = 0
where
a, b and c are real numbers and a ≠ 0
To find the roots of such equation, we use the formula,
(root1,root2) = (-b ± √b2-4ac)/2
The term b2-4ac is known as the discriminant of a quadratic equation. It tells the nature of the roots.
If the discriminant is greater than 0, the roots are real and different.
If the discriminant is equal to 0, the roots are real and equal.
If the discriminant is less than 0, the roots are complex and different.
let userInput = prompt("Input a Number")
for (let a = 0; a <= userInput; a++) {
console.log(a)
}
//QUADRATIC FORMULA FUNCTION
let minus, plus;
let a = prompt("Enter the value for A:");
let b = prompt("Enter the value for B:")
let c = prompt("Enter the value for C:")
let squareRoot = (b*b) - (4*a*c);
// Conditions for Minus or Plus
if (squareRoot > 0) {
minus = (-b - Math.sqrt(squareRoot))/(2 * a);
plus = (-b + Math.sqrt(squareRoot))/(2 * a);
//Result
alert(`The roots of the Quadratic Equation ${minus} and ${plus}`);
}
else if(squareRoot == 0) {
minus = (-b - 0 / (2 * a));
plus = (-b + 0 / (2 * a));
//result
alert(`The roots of the Quadratic Equation are ${minus} and ${plus}`);
}
Top comments (0)