不完全从double转换为int - 似乎问题在于CPU指令

时间:2010-11-29 06:33:46

标签: c++ qt cpu floating-accuracy

我调试代码时感到很惊讶。这里我提供示例代码

#include<QMessageBox>
#include<iostream>
#include<math.h>
#include<QApplication>
using namespace std;

class MyMessageBox: public QMessageBox
{
    public:
        MyMessageBox(string message,QWidget *parent=0) :
            QMessageBox(
                QMessageBox::NoIcon,
                QString("ErrorMessage"),
                QString(message.c_str()),
                QMessageBox::Ok,
                parent,
                Qt::Widget)
        {
        }
};

void Hai()
{
    int tempi = 4;
    double a = pow(10,tempi);
    int temp = int(pow(10,tempi));

    //int temp=a;

    MyMessageBox mb1((QString::number(pow(10,tempi))+
                      " *** "+
                      QString::number(temp)).toStdString());
    mb1.exec();
}

int main(int argc, char * argv[])
{

    QApplication app(argc,argv);
    Hai();

    return app.exec();
}

结果是,

10000 *** 9999

主要的一点是,这件事只发生在力量4(= pow(x,4),而不是任何其他力量。

修改

我尝试使用Visual Studio的最小代码,但它完全产生10,000。但是,在我明确地进行类型转换之前,它从未编译过。代码如下:

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

using namespace std;

void Hai()
{
    int tempi = 4;
    double a=pow(10.0,tempi);
    int temp=pow(10.0,tempi);

    cout << " a " << a << " temp " << temp << endl ;
}

int main(int argc, char * argv[])
{
    Hai();
    return 1;
}

3 个答案:

答案 0 :(得分:2)

你的问题是你的浮点运算的结果是9999.9999999 ...所以int(...)int(9999.9999999...)当然是9999.由于浮点运算很少是准确的,你必须不要写你的代码以期望它们。在这种情况下,您可以使用舍入功能。

正如评论中指出的那样,pow(10,4)的实现极不可能产生正整数,因此您的示例可能存在缺陷。但是,这一点仍然存在:不要指望浮点结果是准确的。

另请参阅:why is 1.2 * 30 = 35?

答案 1 :(得分:0)

记住pow(10,4)和pow(10.0,4)以及pow(10.0,4.0)不会调用相同的函数。

答案 2 :(得分:0)

没有标准可以保证pow功能的准确性。负责任的图书馆供应商试图像这样得到简单的确切案例,但如果你想编写好的可移植代码,就不能依赖于此(如你的经验所示)。

如果您需要精确计算的小整数幂,请使用重复乘法(或用于此目的的库函数)计算它们,而不是调用pow