C++ Program to Find All Square Roots of a Quadratic Equation

Here is a C++ program to find the roots of a quadratic equation. Any quadratic equation can be represented as ax2 + bx + c = 0, where a, b and c are constants( a can't be 0) and x is unknown variable.

For Example
2x2 + 5x + 3 = 0 is a quadratic equation where a, b and c are 2, 5 and 3 respectively.

To calculate the roots of quadratic equation we can use below formula. There are two solutions of a quadratic equation.
x = (-2a + sqrt(D))/2
x = (-2a - sqrt(D))/2
where, D is Discriminant, which differentiate the nature of the roots of quadratic equation.

C++ Program to find all square roots of a quadratic equation

```#include <iostream>
#include <cmath>

using namespace std;

int main() {
float a, b, c, determinant, root1, root2, real, imag;
cout << "Enter coefficients a, b and c of quadratic equation \n";
cin >> a >> b >> c;

/* Calculate determinant */
determinant = b*b - 4*a*c;

if(determinant >= 0) {
root1= (-b + sqrt(determinant))/(2 * a);
root2= (-b - sqrt(determinant))/(2 * a);
cout << "Square roots are " << root1 <<
"  " << root2;
} else {
real= -b/(2*a);
imag = sqrt(-determinant)/(2 * a);
cout << "Square roots are " << real << "+" << imag << "i , "
<< real << "-" << imag << "i";
}

return 0;
}
```
Output
```Enter coefficients a, b and c of quadratic equation
3 7 2
Roots of 3.00x^2 + 7.00x + 2.00 = 0 are
-0.33 and -2.00
```

Recommended Posts
 C++ Program to Find Quotient and Remainder C++ Program to Calculate Standard Deviation C++ Program to Calculate Average Percentage Marks C++ Program to Find Average of Numbers Using Arrays C++ Program to Find Largest Element of an Array C++ Program to Find Smallest Element in Array C++ Program to Find LCM and GCD of Two Numbers C++ Program to Convert Fahrenheit to Celsius C++ Program to Find Power of a Number C++ Program to Check for Armstrong Number C++ Program to Check Prime Number All C++ Programs