如何检查float是否为整数? [英] How to check if float is a whole number?

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

问题描述

对于printf函数,有一些函数可以使用%g,如果float为3.00,它将显示整数 3 code> 3.01 如果它实际上是一个浮点数,有什么办法你可以通过一些代码这样做吗?

There is some kind of function for the printf function in which you can use %g, which will show the whole number 3 if the float is 3.00 and will show 3.01 if it's actually a float, is there any way you can do this through some code?

推荐答案

没有真正的简单答案



整数值在float和double格式中有确切的表示。因此,如果真的已经是积分,您可以使用:

There isn't really a simple answer

Integral values do have exact representations in the float and double formats. So, if it's really already integral, you can use:

f == floor(f)

但是,如果你的值是一个计算的结果,零分数部分,那么你将需要关心,你可能有一个非常接近一个整数,但不是真的,确切地,到最后位相同。

However, if your value is the result of a calculation which at one point involved any sort of non-zero fractional part, then you will need to be concerned that you may have something very close to an integer but which isn't really, exactly, to-the-last-bit the same. You probably want to consider that to be integral.

可以这样做:

fabs(f - round(f)) < 0.000001

虽然我们是主题,但对于纯粹主义者,我们应该注意 int i = f; double i = f; 将根据FPU模式进行舍入,而 round(3)将使中途离开零的半途径。

And while we are on the subject, for the purists, we should note that int i = f; or double i = f; will round according to the FPU mode whereas round(3) will round half-way cases away from zero.

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

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