测试一个浮点数是整数 [英] Test if a floating point number is an integer

查看:223
本文介绍了测试一个浮点数是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码(C#3)

 双D; 
如果(D ==(双)(INT)D)...;




  1. 有没有更好的方式来做到这一点?

  2. 对于外来的原因,我想避免双投这样;有什么好的办法比这还存在着其他? (即使它们没有那么好)



注:的几个人指出(重要)点==往往是有问题的改编浮点。在这种情况下,我希望在0范围的值几百,他们都应该是整数(非整数的错误),所以如果这些点不应该对我来说是一个问题。


解决方案

  D == Math.Floor(D)

确实换句话说同样的事情



NB:希望你知道你必须要做这种事情的时候非常小心;花车/双打会很容易积累误差微乎其微,使得精确比较(像这样)失败没有明显的理由。


This code works (C# 3)

double d;
if(d == (double)(int)d) ...;

  1. Is there a better way to do this?
  2. For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)

Note: Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.

解决方案

d == Math.Floor(d)

does the same thing in other words.

NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason.

这篇关于测试一个浮点数是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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