无法确定并打印出从int到float隐式铸造的截断误差
用书学习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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为
0.000000
是正确的。 C99 6.3.1.8p1说:因此,在
fi
中,i
转换为float
,产生与f
相同的值。我不确定您的书的编译器如何获得3.000000
。如果您真的想查看截断错误,请执行
(double)f -i
。I think
0.000000
is correct. C99 6.3.1.8p1 says:So in
f-i
, thei
is converted tofloat
, yielding the same value asf
. I am not sure how your book's compiler could have got3.000000
.If you really want to see the truncation error, do
(double)f - i
.