I am trying to brush up on C after about 12+ years, which was two semesters at college. This program works, but I am poor on recursion and wonder if there are some tips that could be offered. Using Borland Turbo C++ 4.5 (yes, old) on win XP pro and win7 pro 32 bit machines.
Code:/* 9.8 Mod listing 6.18 to all cases of integer powers using recursion */ #include <stdio.h> double power(double a, int b); /* function prototype */ int main (void) { double x, xpow; int n; printf("Enter a number and the integer power to which\n"); printf("the number will be raised. Enter q to quit.\n"); while(scanf("%lf%d", &x, &n) == 2) { xpow = power(x,n); printf("%.3e to the power %d is %.3e\n", x, n, xpow); } return 0; } double power(double a, int b) /* POWER function */ { double pow = 1; int b1; if (b == 0) /* case of any number raised to 0 is 1 */ return 1.0; else if (a == 0.0) /* case of 0 to any power but 0 is 0 */ return 0.0; else /* do non 0 pos and neg powers and numbers */ { if (b > 0) /* normalize the power to a positive number */ b1 = b; /* since fractions are not as accurate */ else b1 = -1 * b; pow = a; /* calculate power doing recursive call */ pow *= power(pow, b1-1); if (b < 0.0) /* case of negative exponents */ pow = 1.0/pow; return pow; } }



2Likes
LinkBack URL
About LinkBacks






