Functions

Additional Example - Reference Variables


PROBLEM:

Consider the calculation of the roots of the quadratic equation ax²+bx+c=0, assuming that a is non-zero:-

Write a function in C++ which will take a, b and c as arguments and returns the roots as function arguments root1 and root2 (as appropriate). The number of roots will be returned through the type specifier.

Write a main program which prompts the user to enter the values of a, b and c. Then after using a call to the function written above, the program will display the number of roots and their values as appropriate.


SOLUTION:

The function has to be sent the arguments a, b and c, it also requires two arguments for the roots. These values will be altered by the program so must be refernec variables. The function returns an integer number for the number of roots. The function declaration will therefore be:-


int root (float a, float b, flot c, float &root1, float &root2);

The rest of the function can now be written.



int root (float a, float b, float c, float &root1, float &root2)
{
	float 	tmp;

	tmp = b*b - 4*a*c;

	if (tmp > 0)
	{
		root1 = (-b + sqrt(tmp))/(2*a);
		root2 = (-b - sqrt(tmp))/(2*a);
		return 2;
	}
	else if (tmp == 0)
	{
		root1 = -b/(2*a);
		return 1;
	}
	else
		return 0;
}
The main program can now be written. Remember to include the function declaration and math.h as the sqrt function was used.

#include <iostream.h>
#include <math.h>

int root (float a, float b, float c, float &root1, float &root2);

main()
{
	float	a,b,c,root1,root2;
	int	num_roots;

	cout << "Enter values for a, b and c\n";

	cin >> a >> b >> c;

	num_roots = root(a,b,c,root1, root2);

	if (num_roots == 2)
		cout << "There are 2 real roots with values  " << root1 
		     << " and " << root2 << " \n";
	else if (num_roots == 1)
		cout << "There is 1  real root with value " << root1 <<" \n";
	else
		cout << "There are no real roots\n";
}


Back to Main Page for Lecture 6