【问题标题】:Unexpected result with pow() function in C++ [duplicate]C ++中pow()函数的意外结果[重复]
【发布时间】:2015-08-28 11:27:00
【问题描述】:

我已经写了这段代码:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int x,n,result;

    cout<<"enter the value"<<endl;
    cin>>x;

    cout<<"enter the power"<<endl;
    cin>>n;

    result=pow(x,n);
    cout<<"the result of power\t"<<x<<"to\t"<<n<<"=\t"<<result;
}

当我分配 x=10 n=2 时,结果是 99 而不是 100。
当我将 x,n,result 更改为 float 类型时,输出为 x=10 n=2 result=100。

谁能解释一下为什么会有这种差异?

【问题讨论】:

  • 先知道pow是一个浮点函数,再看floating point math is not broken。
  • 您(在不知不觉中)使用浮点计算。将浮点数转换为整数是错误的来源。如果您改为直接打印pow(x,n),您会得到更合理的答案。
  • 投反对票,因为这个问题对任何人都没有帮助。
  • @23ars 我不同意。不过,很可能是重复的,但如果是这样,问题应该被关闭,而不是被否决

标签: c++


【解决方案1】:

阅读 C++ 参考资料怎么样?这里是what you can find about pow():

double pow(双底,双指数);
float pow(浮点数,浮点数);
long double pow (long double base, long double exponent);
双 pow(Type1 基数,Type2 指数); // 额外的重载

如您所见,整数参数没有pow(),但您可以使用强制转换,例如:

int x, n;  
{...}  
double result=pow(double(x),double(n));

更多信息写在这里:Why is my integer math with std::pow giving the wrong answer?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2013-08-17
    • 2018-06-30
    • 1970-01-01
    • 2018-11-05
    • 2015-12-25
    • 1970-01-01
    相关资源
    最近更新 更多