名稱空間
變體
操作

std::numeric_limits<T>::round_style

來自 cppreference.com
< cpp‎ | 型別‎ | 數值限制
 
 
 
 
 
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

[編輯] 另請參閱

指示浮點舍入模式
(enum) [編輯]