|
|
|
|
|
|
|
// Postcondition:
// Function value == x to the n power
{
int result; // Holds intermediate powers of x
result = 1;
while (n > 0)
{
result = result * x;
n--;
}
return result;
} |
|
|
|
|
|
|
|
|
Notice the notation that we use in the postcondition of a value-returning function. Because a value-returning function returns a single value, it is most concise if you simply state what that value equals. Except in complicated examples, the postcondition looks like this: |
|
|
|
|
|
|
|
|
// Postcondition
// Function value == |
|
|
|
|
|
|
|
|
Another function that is frequently used in calculating probabilities is the factorial. For example, 5 factorial (written 5! in mathematical notation) is 5 × 4 × 3 × 2 × 1. Zero factorial is, by definition, equal to 1. This function has one integer parameter. As with the Power function, we use repeated multiplication, but we decrement the multiplier on each iteration. |
|
|
|
|
|
|
|
|
int Factorial( /* in */ int x ) // Number whose factorial is
// to be computed
// This function computes x!
// Precondition:
// x >= 0 && x! <= INT_MAX
// Postcondition:
// Function value == x!
{
int result; // Holds partial products
result = 1;
while (x > 0)
{
result = result * x;
x--;
}
|
|
|
|
|
|