checking for equality between an int and float in C

后端 未结 3 486
感动是毒
感动是毒 2020-12-21 09:55

I came across this piece of code :

int x=3;
float y=3.0;
if(x==y)
  printf(\"x and y are equal\");
else
  printf(\"x and y are not equal\");
相关标签:
3条回答
  • 2020-12-21 10:14

    When you try to compare an int with a float, the int gets converted to float first.

    So 3 == 3.0f actually tests float(3) == 3.0f, which is true.

    On the other hand, 3 == 3.1f tests float(3) == 3.1f, which is false.

    0 讨论(0)
  • 2020-12-21 10:14

    In this question x is an integer value whereas y is a float value... an integer value and a float value cannot be equated...so inorder to check equality we have to typecast either float to integer or vice versa... Hope this may help to clear your concept

    0 讨论(0)
  • 2020-12-21 10:24

    Comparisons between arithmetic types are subject to the so-called usual arithmetic conversions (§5/9, §5.9/2, §5.10/1). Emphasis mine.

    Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

    — If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.

    — If either operand is of type long double, the other shall be converted to long double.

    — Otherwise, if either operand is double, the other shall be converted to double.

    Otherwise, if either operand is float, the other shall be converted to float.

    — Otherwise, the integral promotions (4.5) shall be performed on both operands. Then the following rules shall be applied to the promoted operands:

    — If both operands have the same type, no further conversion is needed.

    — Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

    — Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

    — Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

    — Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

    0 讨论(0)
提交回复
热议问题