命名空间
变体
操作

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_ROUNDSstd::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

[编辑] 参见

指示浮点舍入模式
(枚举) [编辑]