Hey all, I think I must be brain damaged, because I am having the dumbest problem. I need a power function for a program, and every single one I use is returning zero at all times. I've tried the math.h pow() and two other functions, one recursive and one non-recursive. The frustrating thing is that this is a tiny, trivial part of what I'm trying to do (find the root of a scalar equation with newton's method), and I can't even seem to get out of the gate. I've tried compiling with g++ and gcc (need g++ for pow() of course), I've tried changing the value of j, swapping j and cx, changing the types of j and cx, and a whole bunch of other junk. Any help would be greatly appreciated. Here's the code, along with the debugging statements that prove to me that I'm getting the wrong answer. ------------------------------------------- Code: #include<math.h> double calcPolyFunctionAtX(double cx); double power(double px, int y); double power2( double base, int exp ); /* ********************* */ /* Main */ int main() { double f; /* unimportant stuff */ f = calcPolyFunctionAtX(x); /* unimportant stuff */ } /* ********************* */ /* Function for calculating polynomial at x */ double calcPolyFunctionAtX(double cx){ int j; double answer; answer = 0; double z; z = 0; for(j=2; j<21; j++){ z = pow(cx, j); printf("The value of cx is %d \n", cx); /* giving me correct values */ printf("The value of j is %i \n\n", j); /* giving me correct values */ /* all of these are giving me incorrect values */ printf("The value of cx to the jth power by custom non-recursive power function is %d \n", power(cx, j) ); printf("The value of j to the cxth power by custom non-recursive power function is %d \n", power(j, cx) ); printf("The value of cx to the jth power by built-in pow function is %d \n", pow(cx, j) ); printf("The value of j to the cxth power by built-in pow function is %d \n", pow(j, cx) ); printf("The value of cx to the jth power by power2 recursive function is %d \n", power2(cx, j) ); printf("The value of j to the cxth power by power2 recursive function is %d \n", power2(j, cx) ); */ } /* other junk */ return answer; } double power(double px, int y){ double product = 1.0; int g; for(g=1; g<=y; g++) { product *= px; } return product; } double power2( double base, int exp ) { int i; if ( exp < 0 ) return 1.0/power2(base, -exp); double product = 1.0; for ( i = 1 ; i <= exp ; i++ ) product *= base; return product; }
The problem is that ya have used the specifier %d for double type......that is not valid.....i suggest try %l or %lf
Thanks! I'll give that a try when I get off work. Although, I'm confused -- those functions all return a double, so shouldn't I specify a double? Thanks!
Yeah.... so I used %f and now all the power functions are returning 0.000000. Any other ideas? Thanks in advance...