// // Program name: quadratic // Author: B. Massingill and students // // Purpose: solve quadratic equations a*x*x + b*x + c = 0 // // Input: // sets of three floating-point numbers a,b,c, read from // standard input // terminated by end-of-file (control-D under Unix, control-Z // under DOS) // Output: // for each set of numbers: // if the equation has no roots, or no real roots, a // message to that effect // if the equation has one or two real roots, the root(s) // (written to standard output) // // C++ programs using math functions (such as sqrt here) begin with the // following four lines #include #include int main() { double a, b, c ; // input coefficients double d ; // b*b - 4*a*c // prompt user cout << "Enter a, b, and c; ctrl-D to end\n" ; // read while there is input: // "cin >> a" returns true if there is input, // false at end of file. while (cin >> a) { // read in other two inputs cin >> b ; cin >> c ; // first check for a=0 if (a == 0.0) { if (b == 0.0) { cout << "No roots\n" ; } else { cout << "One root: " << c/b << endl ; } } else { d = b*b - 4*a*c ; if (d < 0) { cout << "No real roots\n" ; } else if (d == 0) { cout << "One root: " << -b /(2*a) << endl ; } else { cout << "Two roots: " << (-b + sqrt(d))/(2*a) << ", " << (-b - sqrt(d))/(2*a) << endl ; } cout << "Enter a, b, and c; ctrl-D to end\n" ; } } // C++ programs end with the following two lines. return 0; }