常数和变量的浮点表示不同吗?
我执行了以下C ++代码,并得到答案“不一样?怪异.....”。最初,我希望“当然,它们是一样的!!!”。我正在使用dev-c ++ 5.11。
#include <iostream>
using namespace std;
int main() {
float p;
p = 0.3;
if ((p-0.3)==0)
cout << "Of course, they are the same !!!\n";
else
cout << "Not the same? Weird.....\n";
return 0;
}
I executed the following C++ code and get the answer "Not the same? Weird.....". Originally I expected to get "Of course, they are the same!!!". I was using Dev-C++ 5.11.
#include <iostream>
using namespace std;
int main() {
float p;
p = 0.3;
if ((p-0.3)==0)
cout << "Of course, they are the same !!!\n";
else
cout << "Not the same? Weird.....\n";
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如Mat指出的那样,这里的问题是
0.3
是双重的。和(double)(float)0.3!= 0.3
。当铸造0.3
浮动时,您会失去精度。将其扔回去不会神奇地撤消整个圆形。As Mat points out, the problem here is that
0.3
is a double. And(double)(float)0.3 != 0.3
. You lose precision when casting0.3
to float. Casting it back does not magically undo the rounding.