【问题标题】:std::pow does not return the expected int value [duplicate]std::pow 不返回预期的 int 值 [重复]
【发布时间】:2015-08-15 15:30:52
【问题描述】:

以下代码返回 99 作为输出。

#include<iostream>
#include <math.h>
using namespace std;
int Solve(int a)
{
    return (pow(a,2));
}
int main()
{
    int a=10;
    cout<<Solve(a)<<endl;
    return 0;
}

我不知道为什么会发生这种情况,而且,它对 5 和 25 也是如此,所以它与 5 的倍数有关。

是电脑坏了还是什么:D

【问题讨论】:

  • 您尝试过std::pow 设计的任何浮点类型吗?
  • 这取决于您的系统。对我来说,它返回 100。可能是在您的系统上它返回 99.99999998,当转换为 int 时将变成 99。

标签: c++ floating-point rounding floating-accuracy c++-standard-library


【解决方案1】:

技术方面:std::pow 没有为int 定义,只为doublefloat 定义。因此,您不能依赖它返回确切的 int 值。您必须预料到舍入错误。

算法方面:使用朴素算法(n 次乘法)计算 n 次方显然需要线性时间。为了提高大功率的性能,std::pow 的大多数实现不使用这种简单的算法。相反,他们使用对数计算功率。这要快得多,但不如天真的方法正确。

因此,如果您需要准确的结果,则必须使用for 循环来计算功率。

【讨论】:

  • 谢谢!我在一个程序中使用了它,其中std::pow 被连续多次调用,当这种情况发生时,它让我大吃一惊。
  • @J.Doe 我知道你在说什么——几个月前我有 std::pow 引起了类似的问题,我正疯狂地试图调试这个问题。 ;-)
猜你喜欢
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 2017-09-07
相关资源
最近更新 更多