next up previous
Next: Explanation of the Program Up: The Code Previous: Pseudocode

C++ code

Here is a code that calculates roots of a quadratic according to the method discussed above.

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

// Compute roots of quadratic equation
// Physics 6720 example

int main()
  float a, b, c, x1, x2;
  float s, d, signb;

  // Get a, b, and c
  cout << "Enter a, b, and c: ";
  cin >> a >> b >> c; 

  d = b*b - 4*a*c;
  signb = 1;
  if(b < 0)signb = -1;
  s = -(b + sqrt(d)*signb)/2;
  x1 = s/a;
  x2 = c/s;

  cout << "Roots are \n" << x1 << " " << x2 << "\n";

Compile the code with the command

   g++ -o quadratic -lm
Note the extra -lm. (Lower case ``l'' as in ``library''.) This linker ``option'' or ``flag'' calls in routines from the math library. In this code we need the sqrt function that appears in the math library. Try compiling without this flag so you can become familiar with linker error messages, which you will doubtless see again!

Carleton DeTar 2007-08-17