Floating point precision does its job here. pow 's actual job is to use log
pow(a, 2) ==> exp(log(a) * 2)
Take a look at the math.h library which says:
<math.h>
/ * Exceeding accuracy when using the 64-bit mantissa for mathematical modeling of FPUs may lead to unexpected results with some of the mathematical functions of MSVCRT. For example, if the value of the returned function is not saved (truncation to the 53-bit mantissa), it calls pow with x and y as integral values ββsometimes produce an unreasonable result .... * /
Just add 0.5 to the return value of pow , and then convert it to int .
b = (int)(pow(a,2) + 0.5);
So the answer to your question
Does pow () use an int data type in C?
Not always. For integer exponentiation, you can implement your own function (this will only work for integers + ve):
int int_pow(int base, int exp) { int result = 1; while (exp) { if (exp & 1) result *= base; exp /= 2; base *= base; } return result; }
haccks
source share