为什么我的整数与std :: pow给出错误的答案? [英] Why is my integer math with std::pow giving the wrong answer?
问题描述
请考虑以下代码:
#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;
}
输出122而不是123。是g ++ 4.7.2(MinGW,Windows XP)中的错误吗?
It outputs "122" instead of "123". Is it a bug in g++ 4.7.2 (MinGW, Windows XP)?
推荐答案
std :: pow()
适用于浮点数,它们没有无限精度,并且可能是你使用的实现 pow()在一个(穷)的方式,使这种缺乏无限精度的标准库的实现成为相关。
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.
但是,您可以轻松地定义自己的版本,使用整数。在C ++ 11中,你甚至可以使它 constexpr
(以便结果可以在编译时可能时计算):
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);
}
这是一个 live example 。
尾递归表单 Dan Nissenbaum ):
constexpr int int_pow(int b, int e, int res = 1)
{
return (e == 0) ? res : int_pow(b, e - 1, b * res);
}
这篇关于为什么我的整数与std :: pow给出错误的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!