在C ++中使用NaN? [英] Using NaN in C++?

查看:586
本文介绍了在C ++中使用NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中使用NaN的最好方法是什么?

What's the best way to use NaNs in C++?

我发现 std :: numeric_limits< double& code>和 std :: numeric_limits< double> :: signaling_NaN()。我想使用 signaling_NaN 表示未初始化的变量,如下所示:

I found std::numeric_limits<double>::quiet_NaN() and std::numeric_limits<double>::signaling_NaN(). I'd like to use signaling_NaN to represent an uninitialized variable as follows:

double diameter = std::numeric_limits<double>::signaling_NaN();

但是,这会分配信号(引发异常)。

This, however, signals (raises an exception) on assignment. I want it to raise an exception on use, not on assignment.

有没有办法使用 signaling_NaN 提出转让的例外?是否有一个好的,可移植的替代 signaling_NaN 在使用时会引发浮点异常?

Is there any way to use signaling_NaN without raising an exception on assignment? Is there a good, portable alternative to signaling_NaN that will raise a floating point exception when used?

推荐答案

查看这些之后,看起来 signaling_NaN 是没有用的。如果启用浮点异常,则调用它将作为处理信号NaN计数,因此它立即引发异常。如果禁用浮点异常,则处理信号NaN会自动将其降级为安静的NaN,因此 signaling_NaN 不会工作。

After looking into this some more, it looks like signaling_NaN is useless as provided. If floating point exceptions are enabled, then calling it counts as processing a signaling NaN, so it immediately raises an exception. If floating point exceptions are disabled, then processing a signaling NaN automatically demotes it to a quiet NaN, so signaling_NaN doesn't work either way.

Menkboy的代码适用,但尝试使用信号NaNs运行到其他问题:没有可移植的方式来启用或禁用浮点异常(如此处此处),如果您依赖对于启用的例外,第三方代码可能会停用它们(如此处所述)。

Menkboy's code works, but trying to use signaling NaNs runs into other problems: there's no portable way to enable or disable floating point exceptions (as alluded to here and here), and if you're relying on exceptions being enabled, third party code may disable them (as described here).

因此,似乎 Motti的解决方案< a>是真正的最佳选择。

So it seems like Motti's solution is really the best choice.

这篇关于在C ++中使用NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆