如何在 C++ 14 上获取 -nan?

How get -nan on C++ 14?

我需要 -nan 仅使用 double 类型和算术。

所以,代码应该是这样的:

double a = ...

cout << a << endl;

-nan

其中 ... 是一些表达式。

如果您的平台使用 IEEE754 浮点数,则 0.0 / 0.0 的计算结果将是 NaN。

或者您可以使用 std::numeric_limits<double>::quiet_NaN(),已检查 std::numeric_limits<double>::has_quiet_NaN 在您的平台上是 true

确实没有带符号的 NaN 这样的东西,尽管 NaN 的表示可能包含可以被 std::cout 拾取的符号位。也许在你的平台上 -0.0 / 0.0 生成一个 "negative" NaN。对于 aNaN 的情况,cout << a 的结果完全取决于编译器。

您可以只使用 std::nan,例如

#include <iostream>
#include <cmath>

int main()
{
    double a = -std::nan("1");

    std::cout << a << std::endl;
}

LIVE DEMO

要获得负 nan,只需将 NaN 表示与 0x80000000 进行或运算即可。您将不得不尝试将地址强制转换为 unsigned char * 或 long long *,或者当然。