比较Double和Int的最佳方式是什么? [英] What's the best way to compare Double and Int?

查看:1367
本文介绍了比较Double和Int的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中的以下代码不起作用:

  int iValue = 0; 
double dValue = 0.0;

bool isEqual = iValue.Equals(dValue);

所以问题是:比较Double和Int的最佳方法是什么?

解决方案

你真的无法以天真的方式比较浮点数和积分值;特别是因为有经典的浮点数 代表性挑战。你可以做的是从另一个减去一个,看看它们之间的差异是否小于你关心的一些精度,像这样:

  int iValue = 0; 
double dValue = 0.0;

var diff = Math.Abs​​(dvalue - iValue);
if(diff< 0.0000001)//需要一些最小阈值来比较浮点数
return true; //项目等于

你真的必须为自己定义什么 code>意味着你例如,您可能需要一个浮点值来舍入到最接近的整数,以便3.999999981将等于4.或者您可能要截断该值,因此它将有效地为3。这一切都取决于您的



编辑:请注意,我选择了0.0000001作为示例阈值...您需要为自己决定什么精度足以比较。只要意识到你需要在 double 的正常代表性范围内,我相信它被定义为 Double.Espilon 。 / p>

The following code in C# doesn't work:

int iValue = 0;
double dValue = 0.0;

bool isEqual = iValue.Equals(dValue);

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

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.

EDIT: 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.Espilon.

这篇关于比较Double和Int的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆