Quadratic Roots


Program Listing

QuadraticRoots.cpp

/****************************************************************************
*                                                                           *
*   Program:    QuadraticRoots                                              *
*                                                                           *
****************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {

//  Get the coefficients

    cout << "Enter the coefficient of x-squared:  " << 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 x-squared:  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 x-squared:  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 x-squared:  2
Enter the coefficient of x:  4
Enter the constant term:  6

The roots are nan and nan



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:25 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/QuadraticRoots.html

Return to Coms 261 home page