How to raise a double value by power of 12?
I have a double which is:
double mydouble = 10;
and I want 10^12, so 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10. I tried
double newDouble = pow(10, 12);
and it re开发者_StackOverflow社区turns me in NSLog: pow=-1.991886
makes not much sense... I think pow isn't my friend right?
try pow(10.0, 12.0). Better yet, #include math.h
.
To clarify: If you don't include math.h, the compiler assumes that pow()
returns an integer. Including math.h brings in a prototype like
double pow(double, double);
So the compiler can understand how to treat the arguments and the return value.
I couldn't even get the program to compile without:
#include <math.h>
When using math functions like this you should ALWAYS include math.h and make sure you are calling the right pow function. Who knows what the other pow function might be ... it could stand for "power wheels" haha
Here's how to compute x^12 with the fewest number of multiplications.
y = x*x*x; y *= y; y *= y;
The method comes from Knuth's Seminumerical Algorithms, section 4.6.3.
That's the right syntax for pow, what format string are you passing to NSLog(…)?
did you try casting to a double:
NSLog(@"(double)pow(10, 12) = %lf", (double)pow(10, 12));
精彩评论