Skip to content

Commit 8f92881

Browse files
Created a C++ Program to Find All Roots of a Quadratic Equation
This program accepts coefficients of a quadratic equation from the user and displays the roots (both real and complex roots depending upon the discriminant).
1 parent 693aada commit 8f92881

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/Quadratic Equation.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <iostream>
2+
#include <cmath>
3+
using namespace std;
4+
5+
int main() {
6+
7+
float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
8+
cout << "Enter coefficients a, b and c: ";
9+
cin >> a >> b >> c;
10+
discriminant = b*b - 4*a*c;
11+
12+
if (discriminant > 0) {
13+
x1 = (-b + sqrt(discriminant)) / (2*a);
14+
x2 = (-b - sqrt(discriminant)) / (2*a);
15+
cout << "Roots are real and different." << endl;
16+
cout << "x1 = " << x1 << endl;
17+
cout << "x2 = " << x2 << endl;
18+
}
19+
20+
else if (discriminant == 0) {
21+
cout << "Roots are real and same." << endl;
22+
x1 = -b/(2*a);
23+
cout << "x1 = x2 =" << x1 << endl;
24+
}
25+
26+
else {
27+
realPart = -b/(2*a);
28+
imaginaryPart =sqrt(-discriminant)/(2*a);
29+
cout << "Roots are complex and different." << endl;
30+
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
31+
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
32+
}
33+
34+
return 0;
35+
}

0 commit comments

Comments
 (0)