Code:
// This program takes three coefficients of the function f(x) = ax^2 + bx + c and figures out the
// value of the determinant, which in turn displays the roots of the function, if any exist.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double a, b, c, xplus, xminus, x, deter;
void read ( double &a, double &b, double &c );
double determinant ( double a, double b, double c );
bool quadplus ( double a, double b, double deter );
bool quadminus ( double a, double b, double deter );
bool quadone ( double a, double b );
bool report ( double a, double b, double c, double xplus, double xminus, double x );
int main()
{
double a, b, c, xplus, xminus, x, deter;
read ( a, b, c );
deter = determinant ( a, b, c );
xplus = quadplus ( a, b, deter );
xminus = quadminus ( a, b, deter );
x = quadone ( a, b );
report ( a, b, c, xplus, xminus, x );
system("Pause");
}
void read ( double &a, double &b, double &c )
{
// Read in the three coefficients:
cout << "Enter the coefficients of a quadratic function f(x) = ax^2 + bx + c:" << endl;
cout << " a = ";
cin >> a;
cout << " b = ";
cin >> b;
cout << " c = ";
cin >> c;
}
double determinant ( double a, double b, double c )
{
// Identify the value of the determinant:
deter = ( pow(b,2.0) - ( 4.0 * a * c ) );
return deter;
}
bool quadplus ( double a, double b, double deter )
{
// Find the addition value of the function if it has two roots:
double xplus;
if ( deter > 0 ) {
xplus = (( -1.0 * b ) + sqrt( deter )) / ( 4.0 * a );
return xplus;
} else;
}
bool quadminus ( double a, double b, double deter )
{
// Find the subtraction value of the functon if it has two roots:
double xminus;
if ( deter > 0 ) {
xminus = (( -1.0 * b ) - sqrt( deter )) / ( 4.0 * a );
return xminus;
} else;
}
bool quadone ( double a, double b )
{
// Find the value of the function if it has one root:
if ( deter == 0 ) {
x = ( -1.0 * b ) / ( 4 * a );
return x;
} else;
}
bool report ( double a, double b, double c, double xplus, double xminus, double x)
{
// Report:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout << setprecision(3);
if ( deter > 0 ) {
cout << "The function f(x) = " << a << "*x^2 + " << b << "*x + " << c <<
" has two real roots:" << endl << " x = " << xplus << endl << " x = " << xminus << endl;
} else if ( deter == 0 ) {
cout << "The function f(x) = " << a << "*x^2 + " << b << "*x + " << c <<
" has one real root:"<< endl << " x = " << x << endl;
} if ( deter < 0 ) {
cout << "The function f(x) = " << a << "*x^2 + " << b << "*x + " << c <<
" has no real roots." << endl;
}
}
Besides the mathematical errors, any methods as to how make the program simpler would also appreciated. Thanks in advance.