std::numeric_limits<T>::signaling_NaN
来自 cppreference.com
< cpp | types | numeric limits
static T signaling_NaN() throw(); |
(直到 C++11) | |
static constexpr T signaling_NaN() noexcept; |
(自 C++11 起) | |
返回特殊值 "signaling 非数字", 如浮点类型 T
所示。仅在 std::numeric_limits<T>::has_signaling_NaN == true 时有意义。在 IEEE 754 中,最常见的浮点数二进制表示中,任何指数位全为 1 且分数位至少有一位为 1 的值都表示 NaN。分数位的哪些值表示静默或信号 NaN 以及符号位是否有意义,是实现定义的。
内容 |
[编辑] 返回值
T
|
std::numeric_limits<T>::signaling_NaN() |
/* 非特化 */ | T() |
bool | false |
char | 0 |
signed char | 0 |
unsigned char | 0 |
wchar_t | 0 |
char8_t (自 C++20 起) | 0 |
char16_t (自 C++11 起) | 0 |
char32_t (自 C++11 起) | 0 |
short | 0 |
unsigned short | 0 |
int | 0 |
unsigned int | 0 |
long | 0 |
unsigned long | 0 |
long long (自 C++11 起) | 0 |
unsigned long long (自 C++11 起) | 0 |
float | 实现定义的 (可能为 FLT_SNAN) |
double | 实现定义的 (可能为 DBL_SNAN) |
long double | 实现定义的 (可能为 LDBL_SNAN) |
[编辑] 说明
NaN 永远不会与自身比较相等。根据 IEEE-754,复制 NaN 不需要保留其位表示形式 (符号和 有效载荷),尽管大多数实现都这样做。
当信号 NaN 用作算术表达式的参数时,可能会引发适当的浮点异常,并且 NaN 会“静默”,也就是说,表达式返回一个静默 NaN。
[编辑] 示例
演示使用信号 NaN 引发浮点异常
运行此代码
#include <cfenv> #include <iostream> #include <limits> #pragma STDC_FENV_ACCESS on void show_fe_exceptions() { int n = std::fetestexcept(FE_ALL_EXCEPT); if (n & FE_INVALID) std::cout << "FE_INVALID is raised\n"; else if (n == 0) std::cout << "no exceptions are raised\n"; std::feclearexcept(FE_ALL_EXCEPT); } int main() { double snan = std::numeric_limits<double>::signaling_NaN(); std::cout << "After sNaN was obtained, "; show_fe_exceptions(); double qnan = snan * 2.0; std::cout << "After sNaN was multiplied by 2, "; show_fe_exceptions(); double qnan2 = qnan * 2.0; std::cout << "After the quieted NaN was multiplied by 2, "; show_fe_exceptions(); std::cout << "The result is " << qnan2 << '\n'; }
输出
After sNaN was obtained, no exceptions are raised After sNaN was multiplied by 2, FE_INVALID is raised After the quieted NaN was multiplied by 2, no exceptions are raised The result is nan
[编辑] 参见
标识可以表示特殊值 "信号非数字" (NaN) 的浮点类型 (公共静态成员常量) | |
[静态] |
返回给定浮点类型的静默 NaN 值 (公共静态成员函数) |
(C++11) |
检查给定数字是否为 NaN (函数) |