C++ pow() function changes behaviour when put inside a function
The problem is that the output of pow
is a floating point double
. In your custom function you convert that output to long long
, which will truncate if the value returned by pow
is slightly low instead of slightly high. See Is floating point math broken?. When you call pow
directly the value is kept as a double
even after the multiplication, and output rounding gives you a more accurate result.
You expect the value returned by pow(100,2)
to be 10000, but instead it might be 9999.99999999999 because of the way floating point works. When converted to integer, that becomes 9999; multiplied by 68, you have 679932.
On the other hand, 9999.99999999999 multiplied by 68 becomes 679999.999999999. That's close enough to 680000 that the output function <<
will round it for you. You can get a more exact figure if you apply output formatting.