remainder, remainderf, remainderl

< c‎ | numeric‎ | math
在标头 <math.h> 定义
float       remainderf( float x, float y );
(1) (C99 起)
double      remainder( double x, double y );
(2) (C99 起)
long double remainderl( long double x, long double y );
(3) (C99 起)
在标头 <tgmath.h> 定义
#define remainder( x, y )
(4) (C99 起)
1-3) 计算浮点除法运算 x/y 的 IEEE 余数。
4) 泛型宏:若任何实参拥有 long double 类型,则调用 remainderl。否则若任何实参拥有整数类型或 double 类型,则调用 remainder。否则调用 remainderf

此函数所计算的除法运算 x/y 的 IEEE 浮点余数,准确地为值 x - n * y,其中值 n 是最接近 x/y 准确值的整数值。|n-x/y| = ½ 时,选择作为偶数的 n

std::fmod() 相反,不保证返回值拥有与 x 相同的符号。

若返回值是 0,则它拥有与 x 相同的符号。

参数

x, y - 浮点值

返回值

若成功,则返回如上定义的除法 x / y 的 IEEE 浮点余数。

若出现定义域错误,则返回实现定义值(受支持平台上为 NaN)。

若出现下溢所致的值域错误,则返回正确结果。

y 为零但不出现定义域错误,则返回零。

错误处理

报告 math_errhandling 中指定的错误。

y 为零则可能出现定义域错误。

若实现支持 IEEE 浮点算术(IEC 60559),则

  • 当前舍入模式无效。
  • 决不引发 FE_INEXACT,结果始终准确。
  • x 为 ±∞ 且 y 非 NaN,则返回 NaN 并引发 FE_INVALID
  • y 为 ±0 且 x 非 NaN,则返回 NaN 并引发 FE_INVALID
  • 若任一实参为 NaN,则返回 NaN。

注解

POSIX 要求x 为无穷大或 y 为零则出现定义域错误。

fmod,但不是 remainder,适于安静地包装浮点类型到无符号整数类型:(0.0 <= (y = fmod( rint(x), 65536.0 )) ? y : 65536.0 + y) 在范围 [-0.065535.0] 内,它对应 unsigned short,但 remainder(rint(x), 65536.0) 在范围 [-32767.0+32768.0] 内,它在 signed short 的范围外。

示例

#include <fenv.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
 
int main(void)
{
    printf("remainder(+5.1, +3.0) = %.1f\n", remainder(5.1,3));
    printf("remainder(-5.1, +3.0) = %.1f\n", remainder(-5.1,3));
    printf("remainder(+5.1, -3.0) = %.1f\n", remainder(5.1,-3));
    printf("remainder(-5.1, -3.0) = %.1f\n", remainder(-5.1,-3));
 
    // 特殊值
    printf("remainder(-0.0, 1.0) = %.1f\n", remainder(-0.0, 1));
    printf("remainder(+5.1, Inf) = %.1f\n", remainder(5.1, INFINITY));
 
    // 错误处理
    feclearexcept(FE_ALL_EXCEPT);
    printf("remainder(+5.1, 0) = %.1f\n", remainder(5.1, 0));
    if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID raised");
}

输出:

remainder(+5.1, +3.0) = -0.9
remainder(-5.1, +3.0) = 0.9
remainder(+5.1, -3.0) = -0.9
remainder(-5.1, -3.0) = 0.9
remainder(+0.0, 1.0) = 0.0
remainder(-0.0, 1.0) = -0.0
remainder(+5.1, Inf) = 5.1
remainder(+5.1, 0) = -nan
    FE_INVALID raised

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.12.10.2 The remainder functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.7.2 The remainder functions (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.10.2 The remainder functions (第 185-186 页)
  • 7.25 Type-generic math <tgmath.h> (第 272-273 页)
  • F.10.7.2 The remainder functions (第 385 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.10.2 The remainder functions (第 254-255 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.7.2 The remainder functions (第 529 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.10.2 The remainder functions (第 235 页)
  • 7.22 Type-generic math <tgmath.h> (第 335-337 页)
  • F.9.7.2 The remainder functions (第 465 页)

参阅

(C99)
计算整数除法的商和余数
(函数)
(C99)(C99)
计算浮点除法运算的余数
(函数)
(C99)(C99)(C99)
计算除法运算的带符号余数,以及商的后三位
(函数)