std::numeric_limits<T>::round_style

来自cppreference.com
 
 
 
 
 
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 表示的值时所用的舍入模式。

标准特化

Tstd::numeric_limits<T>::round_style 的值
/* 未特化 */std::round_toward_zero
boolstd::round_toward_zero
charstd::round_toward_zero
signed charstd::round_toward_zero
unsigned charstd::round_toward_zero
wchar_tstd::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
shortstd::round_toward_zero
unsigned shortstd::round_toward_zero
intstd::round_toward_zero
unsigned intstd::round_toward_zero
longstd::round_toward_zero
unsigned longstd::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_ROUNDSstd::fegetround 获得更改后的值。

示例

十进制值 0.1 不能表示成二进制浮点数类型。在存储于 IEEE-754 double 时,它落入 0x1.9999999999999*2-4
0x1.999999999999a*2-4
之间。舍入到最近可表示结果导致 0x1.999999999999a*2-4

同样地,十进制值 0.30x1.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 中存储
向最近可表示值舍入

参阅

指示浮点数舍入模式
(枚举)