当我调试我的代码时,我感到很惊讶。这里我提供示例代码
#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;
}
最佳答案
你的问题是你的浮点运算的结果是 9999.9999999... 所以 int(...)
是 int(9999.9999999...)
这, 当然是 9999。由于浮点运算很少是精确的,因此您在编写代码时一定不要期望它们是精确的。在这种情况下,您可以使用舍入函数。
正如评论中所指出的,您对 pow(10,4)
的实现极不可能不产生正整数,因此您的示例可能存在缺陷。然而,重点仍然存在:永远不要期望浮点结果是准确的。
关于c++ - 不完全从 double 转换为 int - 似乎问题出在 CPU 指令中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4301375/