-1
int a=pow(100,2);//line 1
int b=ceil(pow(100,2));//line 2
cout<<pow(100,2);//line 3

line 1 gives a=9999 on printing the value of a

line 2 gives b=10000 on printing value of b

line 3 prints 10000

I understood that pow give value 9999.9999 so ceil func. in line 2 gives it the upper value.

But why didn't cout print 9999.9999

Can anyone explain why pow behave like this return decimal value pow is just a power function why doesn't it simply give 100*100 as answer?

Shaurya Uppal
  • 3,410
  • 31
  • 31

2 Answers2

3

In the cout statement, pow(100, 2) is indeed a double-precision value and slightly below 10000 (by a well-known effect of the pow function), but the default accuracy setting of cout causes rounding and output as an integer.

1

The reason is due to pow taking two double values as arguments (and returning a double) and is typically implemented such that pow(x, y) is exp(y log x). This "goes off" for even seemingly trivial input values. See Is floating point math broken?

Note that std::pow has overloads for integral types which can be helpful when working in integer arithmetic.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483