【发布时间】:2011-01-31 07:47:07
【问题描述】:
以下是 cmets 的示例:
class Program
{
// first version of structure
public struct D1
{
public double d;
public int f;
}
// during some changes in code then we got D2 from D1
// Field f type became double while it was int before
public struct D2
{
public double d;
public double f;
}
static void Main(string[] args)
{
// Scenario with the first version
D1 a = new D1();
D1 b = new D1();
a.f = b.f = 1;
a.d = 0.0;
b.d = -0.0;
bool r1 = a.Equals(b); // gives true, all is ok
// The same scenario with the new one
D2 c = new D2();
D2 d = new D2();
c.f = d.f = 1;
c.d = 0.0;
d.d = -0.0;
bool r2 = c.Equals(d); // false! this is not the expected result
}
}
那么,您对此有何看法?
【问题讨论】:
-
为了让事情变得陌生,
c.d.Equals(d.d)和c.f.Equals(d.f)一样计算为true -
不要将浮点数与 .Equals 等精确比较进行比较。这简直是个坏主意。
-
@Thorsten79:这与这里有什么关系?
-
这是最奇怪的。对 f 使用 long 而不是 double 会引入相同的行为。并添加另一个短字段再次更正它......
-
奇怪——它似乎只发生在两者都是相同类型(浮点或双精度)时。将一个更改为浮点数(或小数),D2 的工作方式与 D1 相同。
标签: c# .net floating-point