与 float 和 float 文字相比的奇怪输出

2022-01-09 00:00:00 floating-point c c++ double-precision
float f = 0.7;
if( f == 0.7 )
    printf("equal");
else
    printf("not equal");

为什么输出不等于?

为什么会这样?

推荐答案

发生这种情况是因为在您的声明中

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)

但正如 Michael 在下面的评论中所建议的,您永远不应该测试浮点值是否完全相等.

But as Michael suggested in the comments below you should never test for exact equality of floating-point values.

相关文章