Namespaces
Variants

modf, modff, modfl

From cppreference.net
< c ‎ | numeric ‎ | math
Common mathematical functions
Functions
Basic operations
(C99)
(C99)
(C99)
(C99) (C99) (C99) (C23)
Maximum/minimum operations
Exponential functions
Power functions
Trigonometric and hyperbolic functions
Nearest integer floating-point
(C99) (C99) (C99)
(C23) (C23) (C23) (C23)
Floating-point manipulation
Narrowing operations
(C23)
(C23)
(C23)
(C23)
(C23)
(C23)
Quantum and quantum exponent
Decimal re-encoding functions
Total order and payload functions
Classification
Error and gamma functions
(C99)
(C99)
(C99)
(C99)
Types
Macro constants
Special floating-point values
Arguments and return values
Error handling
Fast operation indicators
定义于头文件 <math.h>
float modff ( float arg, float * iptr ) ;
(1) (C99 起)
double modf ( double arg, double * iptr ) ;
(2)
long double modfl ( long double arg, long double * iptr ) ;
(3) (C99 起)
1-3) 将给定的浮点数值 arg 分解为整数部分和小数部分,两部分均保持与 arg 相同的类型和符号。整数部分(以浮点格式)存储于 iptr 所指向的对象中。

目录

参数

arg - 浮点数值
iptr - 指向浮点数值的指针,用于存储整数部分

返回值

若无错误发生,则返回与 arg 同符号的小数部分。整数部分被存入 iptr 所指向的值。

返回值与存储在 * iptr 中的数值之和即为 arg (需考虑舍入误差)。

错误处理

此函数不受 math_errhandling 中指定的任何错误影响。

如果实现支持 IEEE 浮点算术 (IEC 60559),

  • 如果 arg 为 ±0,则返回 ±0,并将 ±0 存储至 * iptr
  • 如果 arg 为 ±∞,则返回 ±0,并将 ±∞ 存储至 * iptr
  • 如果 arg 为 NaN,则返回 NaN,并将 NaN 存储至 * iptr
  • 返回值是精确的, 当前舍入模式 将被忽略。

注释

此函数的行为如同按以下方式实现:

double modf(double value, double *iptr)
{
#pragma STDC FENV_ACCESS ON
    int save_round = fegetround();
    fesetround(FE_TOWARDZERO);
    *iptr = std::nearbyint(value);
    fesetround(save_round);
    return copysign(isinf(value) ? 0.0 : value - (*iptr), value);
}

示例

#include <float.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
    double f = 123.45;
    printf("给定数字 %.2f 或十六进制格式 %a,\n", f, f);
    double f3;
    double f2 = modf(f, &f3);
    printf("modf() 生成 %.2f + %.2f\n", f3, f2);
    int i;
    f2 = frexp(f, &i);
    printf("frexp() 生成 %f * 2^%d\n", f2, i);
    i = ilogb(f);
    printf("logb()/ilogb() 生成 %f * %d^%d\n", f / scalbn(1.0, i), FLT_RADIX, i);
    // 特殊值
    f2 = modf(-0.0, &f3);
    printf("modf(-0) 生成 %.2f + %.2f\n", f3, f2);
    f2 = modf(-INFINITY, &f3);
    printf("modf(-Inf) 生成 %.2f + %.2f\n", f3, f2);
}

可能的输出:

给定数字 123.45 或十六进制格式 0x1.edccccccccccdp+6,
modf() 生成 123.00 + 0.45
frexp() 生成 0.964453 * 2^7
logb()/ilogb() 生成 1.92891 * 2^6
modf(-0) 生成 -0.00 + -0.00
modf(-Inf) 生成 -INF + -0.00

参考文献

  • C23 标准 (ISO/IEC 9899:2024):
  • 7.12.6.12 modf 函数 (p: TBD)
  • F.10.3.12 modf 函数 (p: TBD)
  • C17 标准 (ISO/IEC 9899:2018):
  • 7.12.6.12 modf 函数 (p: TBD)
  • F.10.3.12 modf 函数 (p: TBD)
  • C11 标准 (ISO/IEC 9899:2011):
  • 7.12.6.12 modf 函数 (p: 246-247)
  • F.10.3.12 modf 函数 (p: 523)
  • C99标准(ISO/IEC 9899:1999):
  • 7.12.6.12 modf函数(第227页)
  • F.9.3.12 modf函数(第460页)
  • C89/C90 标准 (ISO/IEC 9899:1990):
  • 4.5.4.6 modf 函数

参见

(C99) (C99) (C99)
向绝对值不大于给定值的最近整数舍入
(函数)
C++ 文档 关于 modf