// Roots of a quadratic equation a*x**2 +b*x +c = 0 // Reads a,b,c and computes the roots using the quadratic formula // Michael Rothstein // 01/29/2014 #include #include using std::cin; using std::cout; using std::endl; int main(){ // Input the data cout << "Enter the coefficients of the quadratic equation: "; double a,b,c; cin >> a >> b >> c; if ( a == 0 ) { // linear equation or nonsense if ( b == 0 ) { // nonsense equation cout << "a is 0 and b is 0; this is not a real equation.\n"; return 0; } else { // linear equation b*x + c = 0 cout << "a is 0 and the root of the equation " << b << "*x + " << c << " = 0 is " << -c/b << endl; return 0; } } else { // Real quadratic equation double discriminant = b*b - 4*a*c; cout << "The equation " << a << "*x**2 + " << b << "*x + " << c << " = 0 "; if ( discriminant == 0 ){ // two equal roots cout << "has two equal roots which are :" << -b/(2*a) << endl; return 0; } else if ( discriminant > 0 ) { // two real roots double d1 = sqrt(discriminant); double root1 = (-b+d1)/(2*a); double root2 = (-b-d1)/(2*a); cout << "has two real roots which are: " << root1 << " and " << root2 << endl; return 0; } else { // two complex roots double imag_part = sqrt(-discriminant)/(2*a); double real_part = (b==0?0:-b/(2*a)); cout << "has two complex roots: " << real_part << " +/- " << imag_part << "*I\n"; return 0; } } }