开发者

Not exactly converts from double to int - seems problem is in CPU instructions

I got surprised when I debugged my code. Here I provide example code

开发者_如何学编程#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();
}

and the result is,

10000 *** 9999

And the main point is, this thing happens only for power 4 (=pow(x,4), not for any other powers.

EDIT:

I tried a minimal code with Visual Studio, but it yields 10,000 exactly. But, it never compiled until I made the type conversion explicitly. The code is given below

#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;
}


Your problem is that the result of your floating-point operation is 9999.9999999... so int(...) is int(9999.9999999...) which, of course, is 9999. Since floating point operations are rarely exact, you must not write your code to expect them to be. In this case, you could use a rounding function.

As was pointed out in the comment, it's extremely unlikely that your implementation of pow(10,4) doesn't yield a positive integer, so your example is probably flawed. However, the point still stands: don't ever expect floating point results to be exact.

See also: why is 1.2 * 30 = 35?


Remember pow(10,4) and pow(10.0,4) and pow(10.0,4.0) don't call the same function.


There is no standard that guarantees the accuracy of the pow function. Responsible library vendors try to get simple exact cases like this right, but you cannot depend on this (as your experience shows) if you want to write good portable code.

If you require small integer powers computed exactly, compute them with repeated multiplication (or with a library function intended for that purpose), not with a call to pow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜