我刚刚阅读了有关浮点值比较的声明
Floating point values shall not be compared using either the == or !=
operators.
Most floating point values have no exact binary representation and have a
limited precision.
如果是这样,比较两个浮点值的最佳方法是什么?
解决方法
以下扩展方法可能有助于实现Kevin的建议:
public static bool IsEqualTo(this double a,double b,double margin) { return Math.Abs(a - b) < margin; } public static bool IsEqualTo(this double a,double b) { return Math.Abs(a - b) < double.Epsilon; }
所以现在你可以这样做:
if(x1.IsEqualTo(x2)) ... if(x1.IsEqualTo(x2,0.01)) ...
只需将IsEqualTo更改为更合适的名称,或将默认边距更改为double.Epsilon(如果需要).