为什么控制变为“其他”的一部分? [英] Why the control goes in “else” part?

查看:131
本文介绍了为什么控制变为“其他”的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison\">Most对于float和double比较结果的有效途径
  <一href=\"http://stackoverflow.com/questions/1839422/strange-output-in-comparison-of-float-with-float-literal\">strange与浮动文字浮动的比较输出


  INT的main()
{
  浮动= 0.8;
  如果(A == 0.8)
    的printf(X \\ n);
  其他
    的printf(Y \\ n);  返回0;
}

虽然 等于 0.8 ,它输出年。


解决方案

0.8不能重新$ P $二进制浮点精确psented。您code 如果(A == 0.8)基本单precision 0.8比较了双precision 0.8,这是不相等的。

要看到自己这一点,请尝试以下code:

  INT的main()
{
    双A = 0.8f;
    双B = 0.8;    的printf(%LX \\ n,*(长×)及一);
    的printf(%LX \\ n,*(*长)和b);
}

它输出:

  3FE99999A0000000
3FE999999999999A

Possible Duplicate:
Most effective way for float and double comparison
strange output in comparison of float with float literal

int main() 
{
  float a = 0.8;
  if (a == 0.8)
    printf("x\n");
  else 
    printf("y\n");

  return 0;
}

Though a is equal to 0.8, it outputs y.

解决方案

0.8 cannot be represented accurately in binary floating-point. Your code if (a == 0.8) basically compares single-precision 0.8 with double-precision 0.8, which are not equal.

To see this for yourself, try the following code:

int main()
{
    double a = 0.8f;
    double b = 0.8;

    printf("%lX\n", *(long *)&a);
    printf("%lX\n", *(long *)&b);
}

It outputs:

3FE99999A0000000
3FE999999999999A

这篇关于为什么控制变为“其他”的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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