Quadratic Roots
Program Listing
 This program will find the two roots of a quadratic equation.
 Unfortunately, it will not be able to distinguish between real roots and complex roots, nor can it distinguish between distinct roots and a double root.
QuadraticRoots.cpp
/****************************************************************************
* *
* Program: QuadraticRoots *
* *
****************************************************************************/
#include <iostream>
#include <string>
using namespace std;
int main() {
// Get the coefficients
cout << "Enter the coefficient of xsquared: " << flush;
float a;
cin >> a;
cout << "Enter the coefficient of x: " << flush;
float b;
cin >> b;
cout << "Enter the constant term: " << flush;
float c;
cin >> c;
// Compute the two roots of the quadratic equation
float root1 = (b + sqrt(b * b  4 * a * c))/(2 * a);
float root2 = (b  sqrt(b * b  4 * a * c))/(2 * a);
cout << endl << "The roots are " << root1;
cout << " and " << root2 << endl;
return 0;
}

Sample Run #1
Enter the coefficient of xsquared: 2
Enter the coefficient of x: 6
Enter the constant term: 4
The roots are 1 and 2

Sample Run #2
Enter the coefficient of xsquared: 2
Enter the coefficient of x: 4
Enter the constant term: 2
The roots are 1 and 1

Sample Run #3
Enter the coefficient of xsquared: 2
Enter the coefficient of x: 4
Enter the constant term: 6
The roots are nan and nan

Return to Lectures page
email me at
robbk@hsc.edu
This page was last modified on Tue Dec 7 16:04:25 1999
.
URL: http://people.hsc.edu/facultystaff/robbk/Coms261/Examples/QuadraticRoots.html
Return to Coms 261 home page