检查浮点数是否为整数 [英] Checking if float is an integer
问题描述
如何检查 float
变量是否包含整数值?到目前为止,我一直在使用:
How can I check if a float
variable contains an integer value? So far, I've been using:
float f = 4.5886;
if (f-(int)f == 0)
printf("yes
");
else printf("no
");
但我想知道是否有更好的解决方案,或者这个解决方案是否有任何(或许多)缺点.
But I wonder if there is a better solution, or if this one has any (or many) drawbacks.
推荐答案
除了已经给出的很好的答案,您还可以使用 ceilf(f) == f
或 floorf(f) == f
.如果 f
是整数,则两个表达式都返回 true
.他们还为 NaN 返回false
(NaN 总是比较 unequal) 和 true
为 ±infinity,并且不会出现溢出用于保存截断结果的整数类型的问题,因为 floorf()
/ceilf()
return float
s.
Apart from the fine answers already given, you can also use ceilf(f) == f
or floorf(f) == f
. Both expressions return true
if f
is an integer. They also returnfalse
for NaNs (NaNs always compare unequal) and true
for ±infinity, and don't have the problem with overflowing the integer type used to hold the truncated result, because floorf()
/ceilf()
return float
s.
这篇关于检查浮点数是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!