如何将float分成整数和小数部分?

The*_*rix 8 c floating-point

我愿意进行精确的操作,为此我需要一种方法将浮点数分成整数和小数部分.这有什么办法吗?

Ede*_*nia 23

math.h库中包含一个名为modf的 函数.使用此功能,您可以执行您想要的操作.

例:

#include <stdio.h>
#include <math.h>

double ftof ()
{
    double floating = 3.40, fractional, integer;

    fractional = modf(floating, &integer);
    printf ("Floating: %g\nInteger: %g\nFractional: %g", floating, integer, fractional); // when using printf, there are no floats

    return fractional;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Floating: 3.40
Integer: 3
Fractional: 0.40
Run Code Online (Sandbox Code Playgroud)

请注意,double在大多数情况下使用比使用更好float,尽管它double 消耗了两倍float(4:8字节)的内存,因此增加了范围和准确性.此外,如果您在打印时需要更大的浮动数字更精确的输出,您可以尝试printf()指数格式说明符,%e而不是%g仅使用浮动小数的最短表示.

  • 我怀疑它使用了modf,但我似乎无法考虑如何分离它.谢谢你的详细解释! (2认同)