summaryrefslogtreecommitdiff
path: root/chapter9/powers.cxx
blob: 3120f3e020ed6267da001e883ac10553357c8969 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// FILE: powers.cxx
// A demonstration program for two recursive functions that compute powers.
#include <cassert>     // Provides assert
#include <cstdlib>     // Provides EXIT_SUCCESS
#include <iostream>  // Provides cin, cout
using namespace std;

double power(double x, int n);
double pow(double x, int n);

int main( )
{
    double x;
    int n;

    cout << "Please type a value for x (double) and n (int) : ";
    cin >> x >> n;
    cout << "The value of x to the n is: " << power(x, n) << endl;

    cout << "Please type a value for x (double) and n (int) : ";
    cin >> x >> n;
    cout << "The value of x to the n is: " << power(x, n) << endl;

    return EXIT_SUCCESS;
}

double power(double x, int n)
{
    double product; // The product of x with itself n times
    int count;

    if (x == 0)
        assert(n > 0);

    if (n >= 0)
    {
        product = 1;
        for (count = 1; count <= n; count++)
            product = product * x;
        return product;
    }
    else
        return 1/power(x, -n);
}

double pow(double x, int n)
{
    if (x == 0)
    {
        assert(n > 0);
        return 0;
    }
    else if (n == 0)
        return 1;
    else if (n > 0)
        return x * pow(x, n-1);
    else // x is nonzero, and n is negative
        return 1/pow(x, -n);
}