std:: nearbyint, std:: nearbyintf, std:: nearbyintl
|
定义于头文件
<cmath>
|
||
| (1) | ||
|
float
nearbyint
(
float
num
)
;
double
nearbyint
(
double
num
)
;
|
(C++23 前) | |
|
/*floating-point-type*/
nearbyint ( /*floating-point-type*/ num ) ; |
(C++23 起) | |
|
float
nearbyintf
(
float
num
)
;
|
(2) | (C++11 起) |
|
long
double
nearbyintl
(
long
double
num
)
;
|
(3) | (C++11 起) |
|
SIMD 重载
(C++26 起)
|
||
|
定义于头文件
<simd>
|
||
|
template
<
/*math-floating-point*/
V
>
constexpr
/*deduced-simd-t*/
<
V
>
|
(S) | (C++26 起) |
|
额外重载
(C++11 起)
|
||
|
定义于头文件
<cmath>
|
||
|
template
<
class
Integer
>
double nearbyint ( Integer num ) ; |
(A) | |
|
S)
SIMD重载对
v_num
执行逐元素的
std::nearbyint
运算。
|
(since C++26) |
|
A)
为所有整数类型提供了额外的重载,这些类型被视为
double
。
|
(since C++11) |
目录 |
参数
| num | - | 浮点数或整数值 |
返回值
返回根据 当前舍入模式 最接近 num 的整数值。
错误处理
此函数不受 math_errhandling 中指定的任何错误影响。
如果实现支持 IEEE 浮点算术 (IEC 60559),
- FE_INEXACT 永远不会被引发。
- 如果 num 是 ±∞,则直接返回该值,不作修改。
- 如果 num 是 ±0,则直接返回该值,不作修改。
- 如果 num 是 NaN,则返回 NaN。
注释
std::nearbyint
与
std::rint
的唯一区别在于
std::nearbyint
从不引发
FE_INEXACT
。
在所有标准浮点格式中,最大可表示的浮点值都是精确整数,因此
std::nearbyint
本身永远不会溢出;然而当结果存储在整型变量中时,可能会溢出任何整数类型(包括
std::intmax_t
)。
如果当前舍入模式为 FE_TONEAREST ,此函数在处理中间值时向偶数舍入(类似于 std::rint ,但不同于 std::round )。
额外的重载并不要求完全按照 (A) 的形式提供。只需确保对于整数类型的实参 num , std :: nearbyint ( num ) 能够产生与 std :: nearbyint ( static_cast < double > ( num ) ) 相同的效果即可。
示例
#include <cfenv> #include <cmath> #include <iostream> #pragma STDC FENV_ACCESS ON int main() { std::fesetround(FE_TONEAREST); std::cout << "四舍五入到最近值:\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 << "向下取整:\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'; }
输出:
四舍五入到最近值: nearbyint(+2.3) = 2 nearbyint(+2.5) = 2 nearbyint(+3.5) = 4 nearbyint(-2.3) = -2 nearbyint(-2.5) = -2 nearbyint(-3.5) = -4 向下取整: 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)
|
获取或设置舍入方向
(函数) |
|
C 文档
关于
nearbyint
|
|