检查是否浮动是一个整数 [英] Checking if float is an integer

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

问题描述

我如何检查是否浮动变量包含一个整数值?到目前为止,我已经使用了:

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 floats.

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

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