-
Notifications
You must be signed in to change notification settings - Fork 124
/
exercise09.c
54 lines (40 loc) · 1.02 KB
/
exercise09.c
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
// C Primer Plus
// Chapter 9 Exercise 8
// Redo Programming Exercise 8, but this time use a recursive function.
#include <stdio.h>
#include <stdlib.h> // prototype for abs()
double power(double base, int exponent);
int main(void)
{
double base, output;
int exponent;
printf("Test power() function:\n");
printf("Enter a :double: base and :int: exponent: ");
while (scanf("%lf %d", &base, &exponent) == 2)
{
output = power(base, exponent);
printf("%f ^ %d = %f \n", base, exponent, output);
printf("Enter a :double: base and :int: exponent: ");
}
return 0;
}
double power(double base, int exponent)
{
double dbl_power;
// handle powers of zero
if (base == 0)
{
if (exponent == 0)
{
printf("Warning: 0 ^ 0 is undefined. Using 1.\n");
return 1.0;
}
else
return 0;
}
if (exponent == 0) return 1; // stop recursion
dbl_power = base * power(base, abs(exponent) - 1); // recursion step
// if exponent is negative, take reciprocal
if (exponent < 0) dbl_power = 1 / dbl_power;
return dbl_power;
}