Skip to main content

Exercise 2.2: quadratic-1.0a.cpp

//quadratic-1.0a.cpp
//Solution to Exercise 2.2
//Adapted from quadratic-1.0.cpp
//Simplified program to solve a quadratic equation.
//Coefficients in code and solutions output to screen.
//Cannot cope with imaginary solutions.
//Steven Bamford

#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  double a = 1.0, b = 3.0, c = 2.0; //coefficients of quadratic 
                                    //a*x*x + b*x + c = 0
  double des;      //variable for the discriminant
  double x1, x2;   //two 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

  //output solutions to screen
  cout << "Coefficients are: a = " << a 
       << ", b = " << b << ", c = " << c << endl;
  cout << "Solutions are: " << x1 << " and " << x2 << endl;

  system("PAUSE");
  return(0);
}