检查是否浮动是一个整数 [英] Checking if float is an integer
问题描述
我如何检查是否浮动
变量包含一个整数值?到目前为止,我已经使用了:
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\n");
else printf("no\n");
但我不知道是否有更好的解决办法,如果此人有任何(或多个)的缺点。
But I wonder if there is a better solution, or if this one has any (or many) drawbacks.
推荐答案
除了已经给,你也可以使用 ceilf(F)==˚F
或罚款答案 floorf(F)==˚F
。这两个前pressions返回真正
如果˚F
是一个整数。他们还返回假
NaN的(的 NaN的比较总是不等)和真正
为±无穷大,并且没有与满溢用来保存截断结果整数类型问题,因为 floorf()
/ ceilf()
收益浮动
秒。
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屋!