Wrong output using power function - C

Function

pow () gives very strange outputs.

I tried various combinations:

#include<stdio.h> #include<math.h> int main() { int d=1; long long n1,n2; while(d<10) { n1=pow(10,d); n2=pow(10,d); d++; printf("%lld %lld\n",n1,n2); } } 

this gives an incorrect conclusion, i.e. 99 instead of 100, etc.

Now, if I delete one of the variables, ans. right. if instead of d, I use a constant, ans correctly. if I accept n1 and n2 as double, ans is correct.

Thus, the presence of two pow () functions with both variables as power and type cast as integers gives a poor result. Why is this weird behavior?

+4
c ++ c
Jun 15 '13 at 10:12
source share
2 answers

This is the case of creating an integer from a floating point value (which truncates decimal numbers, not rounding it off), and also that pow(x, y) translates to exp(log(x) * y) , which will lead to the result, which is NOT EXACTLY the same as x y - an almost approximate value as a floating point value, for example 99.9999996 (or 100.00002) for 10 2 .

If you want to round it, use round(pow(x, y)) .

+3
Jun 15 '13 at 10:17
source share

When you use pow with variables, its result is double . The int assignment truncates it, and you get 99 instead of 99.9999999.

Using pow without variables is optimized by the compiler (this is computed at compile time).

+2
Jun 15 '13 at 10:15
source share



All Articles