在浮浮字面比较奇怪的输出 [英] strange output in comparison of float with float literal

查看:90
本文介绍了在浮浮字面比较奇怪的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

float f = 0.7;
if( f == 0.7 )
    printf("equal");
else
    printf("not equal");

为什么输出不等于

为什么会出现这种情况?

Why does this happen?

推荐答案

这是因为在你的声明

  if(f == 0.7)

0.7被视为双。尝试0.7f,确保值被视为一个float:

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.

这篇关于在浮浮字面比较奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆