价格!=价格? - 页 8

 

对于那些跳过所有障碍并尝试过所有解决方案的人来说,这是我为自己写的一个相当可靠的解决方案。

如果你还在寻找解决方案,这意味着你遇到了这样的情况。

将107.123111111和107.123999进行比较,结果是107.123107124 进行比较,因为有双重四舍五入的差异。

这里是我对这个问题的解决方案,它不考虑+1和-1的范围,以消除 比较中的双舍入差异。


试试这个。

      // double compare by leoa451
        int CompDoubleE0L1M2(double DoubleA, double DoubleB, int PointsToCompare)
      {
         int IntForDoubleA = (int)(MathFloor(MathPow(10,PointsToCompare) * DoubleA));
         int IntForDoubleB = (int)(MathFloor(MathPow(10,PointsToCompare) * DoubleB));
         
         if(IntForDoubleA >= IntForDoubleB-1 && IntForDoubleA <= IntForDoubleB+1) { return 0; }         // if doubleA within +1/-1 range of doubleB (to compensate for the double rounding veriance)
         else if(IntForDoubleA < IntForDoubleB) { return 1; }                                           // if doubleA < doubleB
         else if(IntForDoubleA > IntForDoubleB) { return 2; }                                           // if doubleA > doubleB
         else return -2;                                                                                // error
      }
 

如果只是简单地比较两个双数,并且需要一个bool的结果,这里有另一个解决方案。

// return true if same double value within digits comparison
bool CompareDoubleEqual(double a, double b, int digits)
{
   if (MathAbs(a - b) > MathPow(10, -digits))
      return(false);

   return(true);
}
 
Dretta: 而这里是另一个解决方案,如果只是简单地比较两个双数,并需要一个bool的结果。
  1. 如果它们相差一个点,你就返回true。这是错的--它们不相等。

  2. 简化

    bool CompareDoubleEqual(double a, double b, int digits)
    {
       return MathAbs(a - b) < MathPow(10, -digits);
    }
    止损后增加订单 - MQL4编程论坛#1.3 2017.05.29