Is “(float)integer == integer” guaranteed to be equal in C#?

前端 未结 5 2028
有刺的猬
有刺的猬 2021-01-07 20:05

While \"we all know\" that x == y can be problematic, where x and y are floating point values, this question is a bit more specific:

5条回答
  •  孤街浪徒
    2021-01-07 20:37

    Yes, the comparison will always be true, whatever value the int is.

    The int will be converted to a float to do the conversion, and the first conversion to float will always give the same result as the second conversion.

    Consider:

    int x = [any integer value];
    float y = x;
    float z = x;
    

    The values of y and z will always be the same. If the conversion loses precision, both conversions will lose the precision in exactly the same way.

    If you convert the float back to int to to the comparison, that's another matter.


    Also, note that even if a specific int value converted to float always results in the same float value, that doesn't mean that the float value has to be unique for that int value. There are int values where (float)x == (float)(x+1) would be true.

提交回复
热议问题