/***************************************************
Implementing the Quadratic Formula
Write a program that reads in the coefficients of
a quadratic polynomial, and prints out its roots.
This time, deal correctly with complex roots!!!
The quadratic formula says that the roots of a
polynomial a x^2 + b x + c are:
____________ ____________
-b - \/ b^2 - 4 a c -b + \/ b^2 - 4 a c
x = ------------------- , -------------------
2 a 2 a
Remember, when b^2 - 4 a c you get imaginary roots,
and they are given by :
______________ ______________
-b - i \/ -b^2 + 4 a c -b + i \/ -b^2 + 4 a c
x = ----------------------- , ----------------------
2 a 2 a
***************************************************/
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// read in the coefficients of a x^2 + b x + c
double a,b,c;
char s;
cout << "Enter coefficients a, b, c: ";
cin >> a >> s >> b >> s >> c;
// compute the common subexpression within squareroot
double d;
d = b*b - 4.0*a*c;
// THE CASE OF COMPLEX ROOTS
if (d < 0)
{
cout << "The roots of the polynomial are ";
cout << -b/(2.0*a) << " + "
<<"(" << -sqrt(-d)/(2.0*a) << ")*i";
cout << " and ";
cout << -b/(2.0*a) << " + "
<< "(" << sqrt(-d)/(2.0*a) << ")*i"
<< endl;
}
// THE CASE OF REAL ROOTS
else
{
// compute x1 and x2, the two roots
cout << "The roots of the polynomial are ";
cout << (-b - sqrt(d))/(2.0*a) << " and ";
cout << (-b + sqrt(d))/(2.0*a) << endl;
}
return 0;
}