std::nearbyint, std::nearbyintf, std::nearbyintl
來自 cppreference.com
定義於標頭檔案 <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< /*數學浮點型別*/ V > constexpr /*推導 SIMD 型別*/<V> |
(S) | (C++26 起) |
額外過載 (自 C++11 起) |
||
定義於標頭檔案 <cmath> |
||
template< class Integer > double nearbyint ( Integer num ); |
(A) | |
1-3) 使用 當前舍入模式,將浮點引數 num 舍入為浮點格式的整數值。 庫為所有 cv-unqualified 浮點型別提供了
std::nearbyint
的過載作為引數型別。(C++23 起)
S) SIMD 過載對 v_num 執行逐元素
std::nearbyint 。
|
(C++26 起) |
A) 為所有整數型別提供了額外的過載,它們被視為 double。
|
(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 << "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) |
獲取或設定舍入方向 (函式) |
C 文件 為 nearbyint
|