std::numeric_limits<T>:: round_style
|
static
const
std::
float_round_style
round_style
;
|
(C++11 前) | |
|
static
constexpr
std::
float_round_style
round_style
;
|
(C++11 起) | |
当无法用浮点类型
T
精确表示的值被存储到该类型对象中时,
std::
numeric_limits
<
T
>
::
round_style
的值标识了该类型所使用的舍入方式。
目录 |
标准特化
T
|
std:: numeric_limits < T > :: round_style 的值 |
| /* non-specialized */ | std::round_toward_zero |
| bool | std::round_toward_zero |
| char | std::round_toward_zero |
| signed char | std::round_toward_zero |
| unsigned char | std::round_toward_zero |
| wchar_t | std::round_toward_zero |
| char8_t (since C++20) | std::round_toward_zero |
| char16_t (since C++11) | std::round_toward_zero |
| char32_t (since C++11) | std::round_toward_zero |
| short | std::round_toward_zero |
| unsigned short | std::round_toward_zero |
| int | std::round_toward_zero |
| unsigned int | std::round_toward_zero |
| long | std::round_toward_zero |
| unsigned long | std::round_toward_zero |
| long long (since C++11) | std::round_toward_zero |
| unsigned long long (since C++11) | std::round_toward_zero |
| float | 通常为 std::round_to_nearest |
| double | 通常为 std::round_to_nearest |
| long double | 通常为 std::round_to_nearest |
注释
这些值是常量,不会反映通过 std::fesetround 所做的舍入更改。变更后的值可通过 FLT_ROUNDS 或 std::fegetround 获取。
示例
十进制值
0.1
无法用二进制浮点类型精确表示。当存储在 IEEE-754
double
中时,其实际值介于
0x1.9999999999999*2
-4
与
0x1.999999999999a*2
-4
之间。通过就近取整后得到可表示值
0x1.999999999999a*2
-4
。
类似地,十进制值
0.3
介于
0x1.3333333333333*2
-2
与
0x1.3333333333334*2
-2
之间,经四舍五入后存储为
0x1.3333333333333*2
-2
。
#include <iostream> #include <limits> auto print(std::float_round_style frs) { switch (frs) { case std::round_indeterminate: return "无法确定舍入样式"; case std::round_toward_zero: return "向零舍入"; case std::round_to_nearest: return "向最接近的可表示值舍入"; case std::round_toward_infinity: return "向正无穷舍入"; case std::round_toward_neg_infinity: return "向负无穷舍入"; } return "未知舍入样式"; } int main() { std::cout << std::hexfloat << "十进制数 0.1 在 double 类型中存储为 " << 0.1 << '\n' << "十进制数 0.3 在 double 类型中存储为 " << 0.3 << '\n' << print(std::numeric_limits<double>::round_style) << '\n'; }
输出:
十进制数 0.1 在 double 类型中存储为 0x1.999999999999ap-4 十进制数 0.3 在 double 类型中存储为 0x1.3333333333333p-2 向最接近的可表示值舍入
参见
|
指示浮点数舍入模式
(枚举) |