I tried following function (as suggested on these forums) to calculate power. However, it is causing program to hang up.
static long ipow(int b, int e) {
long r = 1;
while (e--) r *= b;
return r;
}
double cfilefn(int a, int b, int c) {
return (ipow(a, b) / (double)c);
}
cfilefn(2,3,4);
The function looks all right. Where is the error and how can it be solved?
CodePudding user response:
The ipow function will misbehave if the second argument is a negative number: it will run for a while and have implementation defined behavior when e reaches INT_MIN. You should modify the test while (e--) r *= b; as:
static long ipow(int b, int e) {
long r = 1;
while (e-- > 0)
r *= b;
return r;
}
Note however that ipow will cause arithmetic overflow for moderately large values of e and since you want a double result from cfilefn, you should use double arithmetics for the power function:
#include <math.h>
double cfilefn(int a, int b, int c) {
return pow(a, b) / c;
}
