0

What's the problem with this code ?

   printf("%d", pow(2, 10));

as format specifier used is integral , it should give an integer value . But it don't . Why so ?

output - 0

Expected output - 1024

Akhil Raj
  • 457
  • 1
  • 4
  • 14
  • I believe the return value is floating point. – Daniel Stevens Dec 25 '15 at 11:42
  • See [here](http://stackoverflow.com/questions/18417788/pow-cast-to-integer-unexpected-result) for a good explanation (casting also wont work on tcc... from what i read) – urban Dec 25 '15 at 11:44

3 Answers3

5

pow return double. You are using wrong specifier to print a double value. This will invoke undefined behavior and you may get either expected or unexpected result. Use %f instead.

 printf("%f", pow(2, 10));
haccks
  • 104,019
  • 25
  • 176
  • 264
4

The pow function from <math.h> returns type double.

The format specifier for double is %f. You used the wrong specifier, so your program causes undefined behaviour. Literally anything could happen.

To fix this, use %f instead.

BTW if you want to compute 2 to the power 10 in integers you can write 1 << 10.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
1

cast to int

printf("%d", (int)pow(2, 10));