0
#include <stdio.h>
#include <math.h>

int main()
{
int i = 11;
printf("%d ^ 2 = %d\n",i,(int)pow(i,2));
getchar();
return 0;
}

In this case instead of getting 121,i am getting 120.What is the mistake i am making? (I really need to print pow(i,2) as an int.)

2 Answers2

5

Casting to integer truncates the fraction, possibly pow returned something like 120.99999998 or so...

Don't cast to (int) and use %g format instead of %d to print double result of pow().

CiaPan
  • 9,381
  • 2
  • 21
  • 35
1

It is to do with rounding from double to int.

As the power is constant why have the overhead.

Stick to

printf("%d ^ 2 = %d\n",i, i*i);
Ed Heal
  • 59,252
  • 17
  • 87
  • 127