Exercise 3.1: polynomial-2.0.cpp
//polynomial-2.0.cpp
//Simple program to solve polynomial equations up to 2nd order.
//Adapts polynomial-1.0.cpp to give better output when
//coefficients a and b are zero.
//Reads coefficients from keyboard and outputs to screen.
//Uses complex numbers for quadratic solutions.
//Steven Bamford
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <complex>
using namespace std;
int main()
{
double a, b, c; //coefficients of polynomial
//a*x*x + b*x + c = 0
const double epsilon = 1.0e-300; //a few magnitudes
//larger than the smallest double number
cout << "Enter coefficients a, b, and c:" << endl;
cin >> a >> b >> c; //read coeffs from keyboard
if (abs(a) < epsilon) //if a is zero
{
if (abs(b) < epsilon)
{//no solution
cout << "There is no solution for a = b = 0!" << endl
<< "a and/or b must be non-zero for a solution" << endl;
}
else
{//linear
double xr; // one real solution
xr = -c/b;
cout << "Solution is: " << xr << endl;
}
}
else //if a is non-zero
{ //quadratic
complex<double> des; //variable for the discriminant
complex<double> x1, x2; //two complex solutions
des = b*b - 4*a*c; //calc discriminant
x1 = (-b + sqrt(des))/(2*a); //solution 1
x2 = (-b - sqrt(des))/(2*a); //solution 2
cout << "Solutions are: " << x1 << " and " << x2 << endl;
}
system("PAUSE");
return(0);
}