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

I just wrote a program to calculate the power of an integer. But the solution was not as expected. It worked for all integers except power 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 result looks something like this:

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

Is it possible to use the pow() function for an int data type?

+8
c exponentiation pow
source share
4 answers

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; } 
+12
source share

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

Double type required

+3
source share

no int pow based. What you suffer is floating point truncation.

pow's built-in function is too limited (input range quickly overflows int). In many cases, int based pow, as in your case, when its powers in 2 can be performed effectively in other ways.

+3
source share

printf("%a", pow(10, 2)) and see what you get; I expect you to see that you are missing 100. Call lround if you want to round, not crop.

+2
source share

All Articles