c++ - Why is my integer math with std::pow giving the wrong answer? -
consider following piece of code:
#include <iostream> #include <cmath> int main() { int = 23; int j = 1; int base = 10; int k = 2; += j * pow(base, k); std::cout << << std::endl; }
it outputs "122" instead of "123". bug in g++ 4.7.2 (mingw, windows xp)?
std::pow()
works floating point numbers, not have infinite precision, , implementation of standard library using implements pow()
in (poor) way makes lack of infinite precision become relevant.
however, define own version works integers. in c++11, can make constexpr
(so result computed @ compile-time when possible):
constexpr int int_pow(int b, int e) { return (e == 0) ? 1 : b * int_pow(b, e - 1); }
here live example.
tail-recursive form (credits dan nissenbaum):
constexpr int int_pow(int b, int e, int res = 1) { return (e == 0) ? res : int_pow(b, e - 1, b * res); }
Comments
Post a Comment