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

45,972

Solution 1

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):

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

Solution 2

there is no int based pow. What you are suffering from is floating point truncation.

an int based pow is too constrained (the range of inputs would quickly overflow an int). In many cases int based pow, like in your case where its powers of 2 can be done efficiently other ways.

Solution 3

printf("%a", pow(10, 2)) and see what you get; I expect you'll see you don't quite get 100. Call lround if you want to round instead of truncating.

Solution 4

The C library function double pow(double x, double y)

It takes double type

Share:
45,972
basanta
Author by

basanta

Updated on December 21, 2020

Comments

  • basanta
    basanta over 3 years

    I was simply writing a program to calculate the power of an integer. But the output was not as expected. It worked for all the integer numbers except for the power of 5.

    My code is:

    #include <stdio.h>
    #include <math.h>
    
    int main(void)
    {
      int a,b;
      printf("Enter the number.");
      scanf("\n%d",&a);
      b=pow(a,2);
      printf("\n%d",b);
    }
    

    The output is something like this:

    "Enter the number. 2
     4
    "Enter the number. 5
     24
    "Enter the number. 4
     16
    "Enter the number. 10
     99
    

    Can't we use pow() function for int data type??