无法确定并打印出从int到float隐式铸造的截断误差

发布于 2025-01-25 17:54:52 字数 513 浏览 2 评论 0原文

用书学习C。在我的书中,类似的代码应该产生“ 3.000000”作为截断错误。这本书还老了,​​但仍处于C99标准。我想念什么?

#include <stdio.h>

int main()
{
    int i;
    float f;

    scanf("%d", &i); // 123456789
    f = i; // implicit type cast

    printf("int: %d with size %d\n", i, sizeof(i)); // int: 123456789 with size 4
    printf("float: %f with size %d\n", f, sizeof(f)); // float: 123456792.000000 with size 4

    printf("error: %f with size %d\n", f-i, sizeof(f-i)); // error 0.000000 with size 4

    return 0;
}

Learning C with a book. In my book, a similar code should have yielded "3.000000" as truncation error. The book is a bit older, still on C99 standard. What am I missing?

#include <stdio.h>

int main()
{
    int i;
    float f;

    scanf("%d", &i); // 123456789
    f = i; // implicit type cast

    printf("int: %d with size %d\n", i, sizeof(i)); // int: 123456789 with size 4
    printf("float: %f with size %d\n", f, sizeof(f)); // float: 123456792.000000 with size 4

    printf("error: %f with size %d\n", f-i, sizeof(f-i)); // error 0.000000 with size 4

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

可遇━不可求 2025-02-01 17:54:52

我认为0.000000是正确的。 C99 6.3.1.8p1说:

否则,如果两个操作数的相应类型是float,则将另一个操作数转换为类型域的不更改的类型,其相应的真实类型为float。

因此,在fi中,i转换为float,产生与f相同的值。我不确定您的书的编译器如何获得3.000000

如果您真的想查看截断错误,请执行(double)f -i

I think 0.000000 is correct. C99 6.3.1.8p1 says:

Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.

So in f-i, the i is converted to float, yielding the same value as f. I am not sure how your book's compiler could have got 3.000000.

If you really want to see the truncation error, do (double)f - i.

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