std::numeric_limits<T>::round_style
< cpp | types | numeric limits
|
static const std::float_round_style round_style;
|
(C++11 前) | |
|
static constexpr std::float_round_style round_style;
|
(C++11 起) | |
std::numeric_limits<T>::round_style 的值鉴别浮点类型 T 要存储无法以 T 表示的值时所用的舍入模式。
标准特化
T |
std::numeric_limits<T>::round_style 的值 |
| /* 未特化 */ | 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 (C++20 起) | std::round_toward_zero |
| char16_t (C++11 起) | std::round_toward_zero |
| char32_t (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 (C++11 起) | std::round_toward_zero |
| unsigned long long (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 作为 " << 0.1 << " 在 double 中存储\n" << "小数 0.3 作为 " << 0.3 << " 在 double 中存储\n" << print(std::numeric_limits<double>::round_style) << '\n'; }
输出:
小数 0.1 作为 0x1.999999999999ap-4 在 double 中存储 小数 0.3 作为 0x1.3333333333333p-2 在 double 中存储 向最近可表示值舍入
参阅
| 指示浮点舍入模式 (枚举) |