问题描述
以下 C# 代码不起作用:
The following code in C# doesn't work:
int iValue = 0;
double dValue = 0.0;
bool isEqual = iValue.Equals(dValue);
那么问题来了:比较 Double 和 Int 的最佳方法是什么?
So, the question: what's the best way to compare Double and Int?
推荐答案
你真的不能用幼稚的方式比较浮点和整数值;特别是,因为有经典的 浮点数 代表性挑战.您可以做的是从另一个中减去一个,看看它们之间的差异是否小于您关心的某个精度,如下所示:
You really can't compare floating point and integral values in a naive way; particularly, since there's the classic floating point representation challenges. What you can do is subtract one from the other and see if the difference between them is less than some precision you care about, like so:
int iValue = 0;
double dValue = 0.0;
var diff = Math.Abs(dvalue - iValue);
if( diff < 0.0000001 ) // need some min threshold to compare floating points
return true; // items equal
您确实必须自己定义 equality
对您意味着什么.例如,您可能希望浮点值向最接近的整数舍入,这样 3.999999981 将等于"4.或者您可能希望截断该值,因此它实际上是 3.这完全取决于您'正在努力实现.
You really have to define for yourself what equality
means to you. For example, you may want a floating point value to round towards the nearest integer, so that 3.999999981 will be "equal" to 4. Or you may want to truncate the value, so it would effectively be 3. It all depends on what you're trying to achieve.
请注意,我选择 0.0000001 作为示例阈值......您需要自己决定什么精度足以进行比较.只要意识到你需要在 double
的正常表示范围内,我认为它被定义为 Double.Epsilon
.
Note that i chose 0.0000001 as an example threshold value ... you need to decide for yourself what precision is sufficient for comparison. Just realize you need to be within the normal representational bounds of double
which I believe is defined as Double.Epsilon
.
这篇关于比较 Double 和 Int 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!