Skip to main content

Exercise 4.2: quadratic-5.0.cpp

//quadratic-5.0.cpp
//Solution to Exercise 4.2

//Adapts quadratic-4.0.cpp to output in better format

//Simple program to solve a quadratic equation.
//Reads coefficients from a file and 
//outputs solutions in good format 
//to a different file.
//Uses complex numbers for solutions
//Steven Bamford

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <complex>
using namespace std;

int main()
{
  double a, b, c;  //coefficients of quadratic 
                   //a*x*x + b*x + c = 0
  complex<double> des;      //variable for the discriminant
  complex<double> x1, x2;   //two complex solutions
  ifstream infile;          //input file buffer
  ofstream outfile;         //output file buffer
  int width = 10;    //width of output fields 
  int precision = 6; //precision of output values
  
  infile.open("quadratic.in");       //assign file to input buffer
  outfile.open("quadratic-5.0.out"); //assign file to output buffer

  while (true)
    {
      infile >> a >> b >> c;       //read data
      
      if (infile.eof()) break; // break loop if at end of file

      des = b*b - 4*a*c;            //calc discriminant
      x1 = (-b + sqrt(des))/(2*a);  /* note des complex so */
      x2 = (-b - sqrt(des))/(2*a);  /* complex sqrt() used */
      
      outfile.setf(ios::fixed, ios::floatfield); //set format
      outfile.precision(precision);           //set precision

      //output solutions to file
      outfile << "(" << setw(width) << x1.real() << ","
	      << setw(width) << x1.imag() << ") , " 
	      << "(" << setw(width) << x2.real() << "," 
	      << setw(width) << x2.imag() << ")" << endl;
    }
  
  infile.close();    //close input file
  outfile.close();   //close output file
  
  return(0);
}