# Quadratic equation in C++

Example for versions
Borland C++ Builder 6,
Microsoft Visual C++ 9 (2008)

This example uses a template class `complex<>`

, provided in STL. All calculations are done in complex numbers, because this allows not to worry about the sign of discriminant and representation of the roots.

Operator `>>`

of `complex`

is overloaded so that it can recognize several formats of the number, so the input constants are read not as integers but as complex numbers without imaginary part. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point and even complex ones.

Operator `<<`

is also overloaded to print the number `x`

as `(x.real(),x.imag())`

, so to print roots without imaginary part as a single double, function `print`

was created.

```
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
void print(int ind, complex<double> x)
{ cout << "x" << ind << " = ";
if (abs(x.imag()) < 1E-6)
cout << x.real() << endl;
else cout << x << endl;
}
int main()
{ complex<double> A, B, C, D;
cout << "A = ";
cin >> A;
if (abs(A)<1E-3)
{ cout << "Not a quadratic equation" << endl;
return 1;
}
cout << "B = ";
cin >> B;
cout << "C = ";
cin >> C;
A *= 2;
D = B*B-A*C*2.0;
if (abs(D)<1E-3)
cout << "x = " << (-B/A).real();
else
{ print(1, (-B+sqrt(D))/A);
print(2, (-B-sqrt(D))/A);
}
return 0;
}
```

## Comments

]]>blog comments powered by Disqus

]]>