与 float 和 float 文字相比的奇怪输出 [英] strange output in comparison of float with float literal

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

问题描述

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.

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

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