std::nearbyint, std::nearbyintf, std::nearbyintl
定义于头文件 <cmath>
|
||
float nearbyint ( float arg ); float nearbyintf( float arg ); |
(1) | (C++11 起) |
double nearbyint ( double arg ); |
(2) | (C++11 起) |
long double nearbyint ( long double arg ); long double nearbyintl( long double arg ); |
(3) | (C++11 起) |
double nearbyint ( IntegralType arg ); |
(4) | (C++11 起) |
参数
arg | - | 浮点值 |
返回值
返回 arg
按照当前舍入模式的最接近整数值。
错误处理
此函数不受制于任何指定于 math_errhandling 的错误。
若实现支持 IEEE 浮点算术( IEC 60559 ),则
- 决不引发 FE_INEXACT
- 若
arg
为 ±∞ ,则返回不修改的参数 - 若
arg
为 ±0 ,则返回不修改的参数 - 若
arg
为 NaN ,则返回 NaN
注意
std::nearbyint
和 rint 之间仅有的区别是 std::nearbyint
决不引发 FE_INEXACT 。
所有标准浮点格式中,最大可表示浮点值都是整数,故 std::nearbyint
自身决不溢出;然而存储结果于整数对象时,结果可能溢出任何整数类型(包含 std::intmax_t )。
若当前舍入模式为 FE_TONEAREST ,则此函数在中点情况向偶数舍入(同 rint ,但不同于 round )。
示例
运行此代码
#include <iostream> #include <cmath> #include <cfenv> int main() { #pragma STDC FENV_ACCESS ON std::fesetround(FE_TONEAREST); std::cout << "rounding to nearest: \n" << "nearbyint(+2.3) = " << std::nearbyint(2.3) << " nearbyint(+2.5) = " << std::nearbyint(2.5) << " nearbyint(+3.5) = " << std::nearbyint(3.5) << '\n' << "nearbyint(-2.3) = " << std::nearbyint(-2.3) << " nearbyint(-2.5) = " << std::nearbyint(-2.5) << " nearbyint(-3.5) = " << std::nearbyint(-3.5) << '\n'; std::fesetround(FE_DOWNWARD); std::cout << "rounding down:\n" << "nearbyint(+2.3) = " << std::nearbyint(2.3) << " nearbyint(+2.5) = " << std::nearbyint(2.5) << " nearbyint(+3.5) = " << std::nearbyint(3.5) << '\n' << "nearbyint(-2.3) = " << std::nearbyint(-2.3) << " nearbyint(-2.5) = " << std::nearbyint(-2.5) << " nearbyint(-3.5) = " << std::nearbyint(-3.5) << '\n'; std::cout << "nearbyint(-0.0) = " << std::nearbyint(-0.0) << '\n' << "nearbyint(-Inf) = " << std::nearbyint(-INFINITY) << '\n'; }
输出:
rounding to nearest: nearbyint(+2.3) = 2 nearbyint(+2.5) = 2 nearbyint(+3.5) = 4 nearbyint(-2.3) = -2 nearbyint(-2.5) = -2 nearbyint(-3.5) = -4 rounding down: nearbyint(+2.3) = 2 nearbyint(+2.5) = 2 nearbyint(+3.5) = 3 nearbyint(-2.3) = -3 nearbyint(-2.5) = -3 nearbyint(-3.5) = -4 nearbyint(-0.0) = -0 nearbyint(-Inf) = -inf
参阅
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) |
使用当前舍入模式的最接近整数 若结果有别则有异常 (函数) |
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) |
最接近整数,中间情况下向远离零舍入 (函数) |
(C++11)(C++11) |
获取或设置舍入方向 (函数) |