nearbyint, nearbyintf, nearbyintl
来自cppreference.com
定义于头文件 <math.h>
|
||
float nearbyintf( float arg ); |
(1) | (C99 起) |
double nearbyint( double arg ); |
(2) | (C99 起) |
long double nearbyintl( long double arg ); |
(3) | (C99 起) |
定义于头文件 <tgmath.h>
|
||
#define nearbyint( arg ) |
(4) | (C99 起) |
4) 泛型宏:若
arg
拥有 long double 类型,则调用 nearbyintl
。否则,若 arg
拥有整数类型或 double 类型,则调用 nearbyint
。否则调用 nearbyintf
。参数值
arg | - | 浮点值 |
返回值
返回 arg
按照当前舍入模式的最接近整数值。
错误处理
此函数不受制于任何指定于 math_errhandling 的错误。
若实现支持 IEEE 浮点算术( IEC 60559 ),则
- 决不引发 FE_INEXACT
- 若
arg
为 ±∞ ,则返回不修改的参数 - 若
arg
为 ±0 ,则返回不修改的参数 - 若
arg
为 NaN ,则返回 NaN
注意
nearbyint
和 rint 之间仅有的区别是 nearbyint
决不引发 FE_INEXACT 。
所有标准浮点格式中,最大可表示浮点值都是整数,故 nearbyint
自身决不溢出;然而存储结果于整数对象时,结果可能溢出任何整数类型(包含 intmax_t )。
若当前舍入模式为 FE_TONEAREST ,则此函数在中点情况向偶数舍入(同 rint ,但不同于 round )。
示例
运行此代码
#include <stdio.h> #include <math.h> #include <fenv.h> int main(void) { #pragma STDC FENV_ACCESS ON fesetround(FE_TONEAREST); printf("rounding to nearest:\nnearbyint(+2.3) = %+.1f ", nearbyint(2.3)); printf("nearbyint(+2.5) = %+.1f ", nearbyint(2.5)); printf("nearbyint(+3.5) = %+.1f\n", nearbyint(3.5)); printf("nearbyint(-2.3) = %+.1f ", nearbyint(-2.3)); printf("nearbyint(-2.5) = %+.1f ", nearbyint(-2.5)); printf("nearbyint(-3.5) = %+.1f\n", nearbyint(-3.5)); fesetround(FE_DOWNWARD); printf("rounding down: \nnearbyint(+2.3) = %+.1f ", nearbyint(2.3)); printf("nearbyint(+2.5) = %+.1f ", nearbyint(2.5)); printf("nearbyint(+3.5) = %+.1f\n", nearbyint(3.5)); printf("nearbyint(-2.3) = %+.1f ", nearbyint(-2.3)); printf("nearbyint(-2.5) = %+.1f ", nearbyint(-2.5)); printf("nearbyint(-3.5) = %+.1f\n", nearbyint(-3.5)); printf("nearbyint(-0.0) = %+.1f\n", nearbyint(-0.0)); printf("nearbyint(-Inf) = %+.1f\n", nearbyint(-INFINITY)); }
输出:
rounding to nearest: nearbyint(+2.3) = +2.0 nearbyint(+2.5) = +2.0 nearbyint(+3.5) = +4.0 nearbyint(-2.3) = -2.0 nearbyint(-2.5) = -2.0 nearbyint(-3.5) = -4.0 rounding down: nearbyint(+2.3) = +2.0 nearbyint(+2.5) = +2.0 nearbyint(+3.5) = +3.0 nearbyint(-2.3) = -3.0 nearbyint(-2.5) = -3.0 nearbyint(-3.5) = -4.0 nearbyint(-0.0) = -0.0 nearbyint(-Inf) = -inf
引用
- C11 standard (ISO/IEC 9899:2011):
- 7.12.9.3 The nearbyint functions (p: 251-252)
- 7.25 Type-generic math <tgmath.h> (p: 373-375)
- F.10.6.3 The nearbyint functions (p: 526)
- C99 standard (ISO/IEC 9899:1999):
- 7.12.9.3 The nearbyint functions (p: 232)
- 7.22 Type-generic math <tgmath.h> (p: 335-337)
- F.9.6.3 The nearbyint functions (p: 463)
参阅
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) |
使用当前舍入模式取整到整数,若结果有误则产生异常 (函数) |
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) |
取整到最接近的整数,在相邻整数正中间时取远离零的数 (函数) |
(C99)(C99) |
获得或设置数字的舍入方向 (函数) |