std::numeric_limits<T>::round_style
来自 cppreference.com
< 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 "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
[编辑] 另请参阅
指示浮点舍入模式 (枚举) |