Why is my integer math with std::pow giving the wrong answer?
c++, floating-point, g++
Solution
`std::pow()` works with floating point numbers, which do not have infinite precision, and probably the implementation of the Standard Library you are using implements `pow()` in a (poor) way that makes this lack of infinite precision become relevant.
However, you could easily define your own version that works with integers. In C++11, you can even make it `constexpr` (so that the result could be computed at compile-time when possible):
constexpr int int_pow(int b, int e)
{
return (e == 0) ? 1 : b * int_pow(b, e - 1);
}
Here is a live example.
Tail-recursive form (credits to Dan Nissenbaum):
constexpr int int_pow(int b, int e, int res = 1)
{
return (e == 0) ? res : int_pow(b, e - 1, b * res);
}
Problem
Consider the following piece of code: ``` #include <iostream> #include <cmath> int main() { int i = 23; int j = 1; int base = 10; int k = 2; i += j * pow(base, k); std::cout << i << std::endl; } ``` It outputs "122" instead of "123". Is it a bug in g++ 4.7.2 (MinGW, Windows XP)?