常数和变量的浮点表示不同吗?

发布于 2025-02-08 08:02:46 字数 348 浏览 1 评论 0原文

我执行了以下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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似梦非梦 2025-02-15 08:02:47

正如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 casting 0.3 to float. Casting it back does not magically undo the rounding.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文