nearbyint
nearbyint, nearbyintf, nearbyintl
在头文件 | | |
---|---|---|
float nearbyintf( float arg | (1) | (since C99) |
double nearbyint( double arg | (2) | (since C99) |
long double nearbyintl( long double arg | (3) | (since C99) |
Defined in header <tgmath.h> | | |
#define nearbyint( arg ) | (4) | (since C99) |
1-3)arg
使用当前舍入模式将浮点参数四舍五入为浮点格式的整数值。
4)类型 - 通用宏:如果arg
有类型long double
,nearbyintl
被调用。否则,如果arg
有整数类型或类型double
,nearbyint
则调用。否则nearbyintf
,分别称为。
参数
arg | - | 浮点值 |
---|
返回值
arg
根据当前舍入模式,返回最接近的整数值。
错误处理
此函数不受math_errhandling中指定的任何错误的影响。
如果实现支持IEEE浮点运算(IEC 60559),
FE_INEXACT
从未被提出
笔记
之间唯一的区别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标准(ISO / IEC 9899:2011):