检查浮点是否为整数的最佳方法 [英] Best way of checking if a floating point is an integer
问题描述
[有几个问题,但没有一个答案是特别明确的,有几个已经过时了当前的C ++标准]。
[There are a few questions on this but none of the answers are particularly definitive and several are out of date with the current C++ standard].
我的研究显示这些是用于检查浮点值是否可以转换为整数类型 T
的主要方法。
My research shows these are the principal methods used to check if a floating point value can be converted to an integral type T
.
-
if(f> = std :: numeric_limits< T> :: min()&& f< = std :: numeric_limits< T> ;: :max()& f ==(T)f))
使用 std
using std::fmod
to extract the remainder and test equality to 0.
使用 std :: remainder
并测试等于0。
第一个测试假设从 f
到 T
实例。不是 std :: int64_t
到 float
,例如。
The first test assumes that a cast from f
to a T
instance is defined. Not true for std::int64_t
to float
, for example.
使用C ++ 11,哪一个是最好的?是否有更好的方法?
With C++11, which one is best? Is there a better way?
推荐答案
使用 std :: fmod(f,1.0)== 0.0
其中 f
是 float
, double
或 long double
。如果您担心使用 float
时不必要的浮点促销的虚假效果,请使用 1.0f
或更全面
Use std::fmod(f, 1.0) == 0.0
where f
is either a float
, double
, or long double
. If you're worried about spurious effects of unwanted floating point promotions when using float
s, then use either 1.0f
or the more comprehensive
std :: fmod(f,static_cast< decltype(f)>(1.0))== 0.0
这将强制,明显在编译时,正确的重载被调用。 std :: fmod(f,...)
的返回值将在[0,1]范围内,与 0.0
以完成整数检查。
which will force, obviously at compile time, the correct overload to be called. The return value of std::fmod(f, ...)
will be in the range [0, 1) and it's perfectly safe to compare to 0.0
to complete your integer check.
如果结果是 f
em>是一个整数,那么在尝试转换之前,请确保它在您选择的类型的允许范围内:否则您可能会调用未定义的行为。我看到你已经熟悉了 std :: numeric_limits
,这可以帮助你。
If it turns out that f
is an integer, then make sure it's within the permitted range of your chosen type before attempting a cast: else you risk invoking undefined behaviour. I see that you're already familiar with std::numeric_limits
which can help you here.
使用 std :: remainder
可能是(i)我是一个Luddite和(ii)它不能在一些编译器部分实现C ++ 11标准,如MSVC12 。我不喜欢涉及铸件的解决方案,因为符号隐藏了相当昂贵的操作,你需要提前检查安全。如果你必须采用你的第一选择,至少用 static_cast< T>(f)
;
My reservations against using std::remainder
are possibly (i) my being a Luddite and (ii) it not being available in some compilers partially implementing the C++11 standard, such as MSVC12. I don't like solutions involving casts since the notation hides that reasonably expensive operation and you need to check in advance for safety. If you must adopt your first choice, at least replace the C-style cast with static_cast<T>(f)
;
这篇关于检查浮点是否为整数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!