Does pow() work for int data type in C? -
this question has answer here:
- strange behaviour of pow function 5 answers
i writing program calculate power of integer. output not expected. worked integer numbers except power of 5.
my code is:
#include <stdio.h> #include <math.h> int main(void) { int a,b; printf("enter number."); scanf("\n%d",&a); b=pow(a,2); printf("\n%d",b); }
the output this:
"enter number. 2 4 "enter number. 5 24 "enter number. 4 16 "enter number. 10 99
can't use pow()
function int data type??
floating point precision doing job here. actual working of pow
using log
pow(a, 2) ==> exp(log(a) * 2)
look @ math.h
library says:
<math.h>
/* excess precision when using 64-bit mantissa fpu math ops can cause unexpected results of msvcrt math functions. example, unless function return value stored (truncating 53-bit mantissa), calls pow both x , y integral values produce non-integral result. ... */
just add 0.5
return value of pow
, convert int
.
b = (int)(pow(a,2) + 0.5);
so, answer question
does pow() work
int
data type in c?
not always. integer exponentiation implement own function (this work +ve integers only):
int int_pow(int base, int exp) { int result = 1; while (exp) { if (exp & 1) result *= base; exp /= 2; base *= base; } return result; }
Comments
Post a Comment