|
|
|
|
|
|
|
A call to the Factorial function might look like this: |
|
|
|
|
|
|
|
|
combinations = Factorial(n) / (Factorial(m) * Factorial(n - m)); |
|
|
|
|
|
|
|
|
Value-returning functions are not restricted to returning numerical results. We can also use them to evaluate a condition and return a Boolean result. Boolean functions can be useful when a branch or loop depends on some complex condition. Rather than code the condition directly into the If or While statement, we can call a Boolean function to form the controlling expression. |
|
|
|
|
|
|
|
|
Suppose we are writing a program that works with triangles. The program reads three angles as floating point numbers. Before performing any calculations on those angles, however, we want to check that they really form a triangle by adding the angles to confirm that their sum equals 180 degrees. We can write a value-returning function that takes the three angles as parameters and returns a Boolean result. Such a function would look like this (recall from Chapter 5 that you should test floating point numbers only for near equality): |
|
|
|
|
|
|
|
|
#include <math.h> // For fabs()
.
.
.
typedef int Boolean;
const Boolean TRUE = 1;
const Boolean FALSE = 0;
.
.
.
Boolean IsTriangle( /* in */ float angle1, // First angle
/* in */ float angle2, // Second angle
/* in */ float angle3 ) // Third angle
// This function checks to see if its three incoming values
// add up to 180 degrees, forming a valid triangle
// Precondition:
// angle1, angle2, and angle3 are assigned
// Postcondition:
// Function value == TRUE, if (angle1 + angle2 + angle3) is
// within 0.00000001 of 180.0 degrees
// == FALSE, otherwise
{
|
|
|
|
|
|