如何获得浮点值的小数部分? [英] How should I obtain the fractional part of a floating-point value?
问题描述
我有一个类型为 float
的变量 x
,我需要它的小数部分.我知道我可以用
I have a variable x
of type float
, and I need its fractional part. I know I can get it with
-
x-floorf(x)
或 -
fmodf(x,1.0f)
我的问题:其中一个总是比另一个更可取吗?它们实际上是一样的吗?我可能会考虑第三种选择吗?
My questions: Is one of these always preferable to the other? Are they effectively the same? Is there a third alternative I might consider?
注意:
- 如果答案取决于我使用的处理器,则将其设置为x86_64,并且如果您可以详细说明其他会很好的处理器.
- 请确保并参考
x
的负值上的行为.我不介意这种行为,但我需要知道这种行为是什么.
- If the answer depends on the processor I'm using, let's make it x86_64, and if you can elaborate about other processors that would be nice.
- Please make sure and refer to the behavior on negative values of
x
. I don't mind this behavior or that, but I need to know what the behavior is.
推荐答案
我可能会考虑第三种选择吗?
Is there a third alternative I might consider?
有专用功能. modff 的存在是为了将数字分解为整数和小数部分./p>
There's the dedicated function for it. modff exists to decompose a number into its integral and fractional parts.
float modff(float arg,float * iptr);
将给定的浮点值 arg
分解为整数和分数零件,每个零件的类型和符号与 arg
相同.不可或缺的部分(以浮点格式)存储在 iptr
指向的对象中.
Decomposes given floating point value arg
into integral and fractional
parts, each having the same type and sign as arg
. The integral part
(in floating-point format) is stored in the object pointed to by iptr
.
这篇关于如何获得浮点值的小数部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!