首页 > 解决方案 > 当使用比较运算符比较具有相同值的 int 和 float 变量时会发生什么?

问题描述

当使用比较运算符比较具有相同值的 int 和 float 变量时会发生什么?

 main( )
  {
    int x = 3 ;
    float y = 3.0 ;
    if ( x == y )
      printf ( "\nx and y are equal" ) ;
    else
      printf ( "\nx and y are not equal" ) ;
   }




output : x and y are equal
What happens when x is compared with y variable?

标签: cimplicit-conversion

解决方案


隐式int转换为类型;你的代码相当于float

if ((float)x == y)

请注意,即使从 aint到 a的转换float失去精度(在您的情况下不会),也会发生这种情况。


推荐阅读