Example Using Reference Parameters

We need a function that returns two values.

,

#include <iostream.h>   // cout
#include <math.h>       // sqrt()

// function prototypes
float calculate_discriminant(float a, float b,
                             float c);

void calculate_quadratic(float a, float b, float c, 
                         float &root1, float &root2);

void main(void)
{
  float a = 1.0f, b = 4.0f, c = 2.0f;
  float root1, root2;
	
  calculate_quadratic(a, b, c, root1, root2);

  cout << "a = " << a << ", b = " << b;
  cout << ", c = " << c << endl;
  cout << "root1 = " << root1 << endl;
  cout << "root2 = " << root2 << endl;
}

/////////////////////////////////////////////////////
// Function: calculate_quadratic
//
// Finds the roots of a quadratic equation
// 
//  Input: 3 floating point numbers representing
//         the coefficients,
// Output: 2 floating point numbers, each
//         representing one of the roots
//
void calculate_quadratic(float a, float b, float c, 
                         float &root1, float &root2)
{
  float pos_numerator, neg_numerator;
  float denominator, discriminant;

  discriminant = calculate_discriminant(a, b, c);

  pos_numerator = -b + float(sqrt(discriminant));
  neg_numerator = -b - float(sqrt(discriminant));
  denominator = 2 * a;

  root1 = pos_numerator / denominator;
  root2 = neg_numerator / denominator;
}


/////////////////////////////////////////////////////
// Function: calculate_discriminant
//
// Computes the discriminant of a quadratic equation
// 
//  Input: 3 floating point numbers representing
//         the coefficients
// Output: a floating point number representing
//         the discriminant
//
float calculate_discriminant(float a, float b, float c)
{
  return b * b - 4 * a * c;
}

Previous page

Back to Lesson 5 Index
Back to Outline