Does pow() work for int data type in C? [duplicate]

Floating point precision is doing its job here. The actual working of pow is using log

pow(a, 2) ==> exp(log(a) * 2)

Look at math.h library which says:
###<math.h>

/* Excess precision when using a 64-bit mantissa for FPU math ops can
cause unexpected results with some of the MSVCRT math functions. For
example, unless the function return value is stored (truncating to
53-bit mantissa), calls to pow with both x and y as integral values
sometimes produce a non-integral 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() work for int data type in C?

Not always. For integer exponentiation you could implement your own function (this will work for 0 and +ve exp only):

unsigned uint_pow(unsigned base, unsigned exp)
{
    unsigned result = 1;
    while (exp)
    {
        if (exp % 2)
           result *= base;
        exp /= 2;
        base *= base;
    }
    return result;
}

Leave a Comment