Write a C++ program to find the roots of a quadratic equation ax2 + bx + c = 0
Write a C++ program to find the roots of a quadratic equation ax2 + bx + c = 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include<iostream> #include<cmath> using namespace std; int main() { int a = 1, b = 2, c = 1; float discriminant; float Actual; float Artificial; float x1, x2; if (a == 0) { cout << "This is not a quadratic equation"; }else { discriminant = b*b - 4*a*c; if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "The roots are real and different." << endl; cout << "Root 1 = " << x1 << endl; cout << "Root 2 = "
<< x2 << endl; } else if (discriminant == 0) { cout << "The roots are real and same." << endl; x1 = (-b + sqrt(discriminant)) / (2*a); cout << "Root 1 = Root 2 =" << x1 << endl; }else { Actual = (float) -b/(2*a); Artificial =sqrt(-discriminant)/(2*a); cout << "The roots are complex and different." << endl; cout << "Root 1 is equal to = " << Actual << " + " << Artificial << "i" <<end; cout << "Root 2 is equal to = " << Actual << " - " << Artificial << "i" <<end; } } return 0; } |