std::numeric_limits<T>::round_style
来自 cppreference.cn
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 "Rounding style cannot be determined"; case std::round_toward_zero: return "Rounding toward zero"; case std::round_to_nearest: return "Rounding toward nearest representable value"; case std::round_toward_infinity: return "Rounding toward positive infinity"; case std::round_toward_neg_infinity: return "Rounding toward negative infinity"; } return "unknown round style"; } int main() { std::cout << std::hexfloat << "The decimal 0.1 is stored in a double as " << 0.1 << '\n' << "The decimal 0.3 is stored in a double as " << 0.3 << '\n' << print(std::numeric_limits<double>::round_style) << '\n'; }
输出
The decimal 0.1 is stored in a double as 0x1.999999999999ap-4 The decimal 0.3 is stored in a double as 0x1.3333333333333p-2 Rounding toward nearest representable value
[编辑] 另请参阅
| 指示浮点舍入模式 (enum) |