c++cpow

wrong output by power function - C


pow() function is giving 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 the wrong output i.e. 99 instead of 100 and like that.

now if i remove one of the variables, ans. is correct. if instead of d, i use a constant, ans is correct. if i take n1 and n2 as double, ans is correct.

So having two pow() functions with both having variables as the power and type casted as integers is giving bad output. Why this strange behaviour??


Solution

  • This is a case of making an integer from a floating point value (which truncates the decimals, not rounding it), along with the fact that pow(x, y) translates to exp(log(x) * y), which will produce a result that isn't PRECISELY the same as xy - just a near approximation as a floating point value, such as 99.9999996 (or 100.00002) for 102.

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