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

后端 未结 11 2107
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条回答
  •  Happy的楠姐
    2020-12-03 19:06

    That's scary. (I wonder what else you'll find.)

    x will be promoted to float, but that's not going to help you. Because of how floats are represented, using == to compare them is unreliable.

    I might suggest something like this (checking for absolute error/difference) instead:

    #define EPSILON 0.0001 
    if (fabs((float)x - y) < EPSILON) { /* Do stuff. */ }
    

    which is a common approach and may be sufficient for your purposes, if your values of x and y are "nice". If you really want to go in depth into the topic of comparing floats, this article probably has more information than you want. It does say about the epsilon method:

    If the range of the expectedResult is known then checking for absolute error is simple and effective. Just make sure that your absolute error value is larger than the minimum representable difference for the range and type of float you’re dealing with.

提交回复
热议问题