Compare two floats

前端 未结 5 1603
小蘑菇
小蘑菇 2020-12-03 01:39
#include 

bool Equality(double a, double b, double epsilon)
{
  if (fabs(a-b) < epsilon) return true;
  return false;
}

I trie

5条回答
  •  孤街浪徒
    2020-12-03 02:38

    Alternatively, you could compare two integers instead. Just multiply your two floats by the desired precision and cast them to integers. Be sure to round up/down correctly. Here is what it looks like:

    BOOL floatcmp(float float1, float float2, unsigned int precision){
       int int1, int2;
    
       if (float1 > 0)
          int1 = (int)(float1 * precision + .5);
       else
          int1 = (int)(float1 * precision - .5);
    
       if (float2 > 0)
          int2 = (int)(float2 * precision + .5);
       else
          int2 = (int)(float2 * precision - .5);
    
       return (int1 == int2);
    }
    

提交回复
热议问题