float 与 float 文字比较的奇怪输出 [英] strange output in comparison of float with float literal
本文介绍了float 与 float 文字比较的奇怪输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
float f = 0.7;
if( f == 0.7 )
printf("equal");
else
printf("not equal");
为什么输出不等于
?
为什么会发生这种情况?
Why does this happen?
推荐答案
发生这种情况是因为在你的陈述中
This happens because in your statement
if(f == 0.7)
0.7 被视为双精度值.尝试 0.7f 以确保将值视为浮点数:
the 0.7 is treated as a double. Try 0.7f to ensure the value is treated as a float:
if(f == 0.7f)
但正如迈克尔在下面的评论中所建议的那样,您永远不应该测试浮点值是否完全相等.
But as Michael suggested in the comments below you should never test for exact equality of floating-point values.
这篇关于float 与 float 文字比较的奇怪输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文