这是错误的双重比较0这样的:doubleVariable == 0? [英] Is it wrong to compare a double to 0 like this: doubleVariable==0?
问题描述
这是确定要做到这一点
double doubleVariable=0.0;
if (doubleVariable==0) {
...
}
还是这个代码将潜在的四舍五入问题的困扰?
Or this code would suffer from potential rounding problems?
推荐答案
都能跟得上它是完全合法的,如果你只打算要与之比较0作为比较的右侧将自动浇铸到一倍。在另一方面,它会产生所有的舍入误差。如果你是反对==比较0.10000001
Nope it's perfectly legal if you are only going to compare against 0 as the right side of comparison will automatically casted to double. On the other hand, it would yield all the round-off errors if you where to compare against == 0.10000001
您可以更好地或阅读浮动的讨论,以0比在这里: C#。 NET:是否安全检查浮点值是否相等,以0
You are better or reading the discussion about float to 0 comparison here: C#.NET: Is it safe to check floating point values for equality to 0?
另外这个讨论是关于花车怪异的精度问题,内容非常丰富:的为什么结果是这个问题有什么不同?
Also this discussion is very informative about weird precision problems on floats: Why the result is different for this problem?
即下面会产生错误的:
double d1 = 1.000001; double d2 =0.000001;
Console.WriteLine((d1-d2)==1.0);
这篇关于这是错误的双重比较0这样的:doubleVariable == 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!