Is relational comparison between int and float directly possible in C?

后端 未结 11 2112
Happy的楠姐
Happy的楠姐 2020-12-03 18:48

I am using Visual Studio 6 with some old time code written in c. I found an issue where the code looks like this..

int x = 3;
float y = 3.0;

if(x == y){
            


        
11条回答
  •  星月不相逢
    2020-12-03 19:03

    Well, I guess you won't be too surpised to hear that comparing floats for equality is a rookie mistake then.

    The problem is that many increments smaller than an integer values can't actually be represented exactly in IEEE floating point. So if you arrive at the float by trying to "index" it up to the value of 3.0 (say in increments of 0.1), it is quite possible your equality comparison can never be true.

    It is also a bad idea just from a type-strength standpoint. You should either convert the float into an int, check for your int being "close enough" (eg < 3.1 and > 2.9 or somesuch), or better yet if you are trying to make that float do double-duty for something like a counter, avoid the whole idea.

提交回复
热议问题