C++ 检查 NaN 数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3437085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check NaN number
提问by MBZ
Is it possible to check if a number is NaN
or not?
是否可以检查一个数字是否NaN
存在?
回答by paxdiablo
Yes, by use of the fact that a NaN
is not equal to any other number, including itself.
是的,通过使用 aNaN
不等于任何其他数字(包括其自身)这一事实。
That makes sense when you think about what NaN
means, the fact that you've created a value that isn't really within your power to represent with "normal" floating point values.
当您考虑这NaN
意味着什么时,这是有道理的,事实上,您已经创建了一个实际上无法用“正常”浮点值表示的值。
So, if you create two numbers where you don't know what they are, you can hardly consider them equal. They maybe but, given the rather large possibility of numbers that it may be (infinite in fact), the chances that two are the same number are vanishingly small :-)
因此,如果您在不知道它们是什么的情况下创建两个数字,则很难将它们视为相等。它们可能是,但是,考虑到数字的可能性相当大(实际上是无限的),两个数字相同的可能性非常小:-)
You can either look for a function (macro actually) like isnan
(in math.h
for C and cmath
for C++) or just use the property that a NaN
value is not equal to itself with something like:
您可以寻找一个函数(实际上是宏)isnan
(在math.h
C 和cmath
C++ 中),或者只是使用NaN
值不等于自身的属性,例如:
if (myFloat != myFloat) { ... }
If, for some bizarre reason, your C implementation has no isnan
(it should, since the standard mandates it), you can code your own, something like:
如果出于某种奇怪的原因,您的 C 实现没有isnan
(它应该,因为标准要求它),您可以编写自己的代码,例如:
int isnan_float (float f) { return (f != f); }
回答by Mr.Ree
Under Linux/gcc, there's isnan(double), conforming to BSD4.3.
在 Linux/gcc 下,有isnan(double),符合 BSD4.3。
C99 provides fpclassify(x)and isnan(x).
(But C++ standards/compilers don't necessarily include C99 functionality.)
C99 提供fpclassify(x)和isnan(x)。
(但 C++ 标准/编译器不一定包含 C99 功能。)
There ought to be some way with std::numeric_limit<>... Checking...
std::numeric_limit<> 应该有一些方法......检查......
Doh. I should have known... This question has been answered before... Checking if a double (or float) is NaN in C++Using NaN in C++?http://bytes.com/topic/c/answers/588254-how-check-double-inf-nan
多。我应该知道......这个问题之前已经回答过...... 检查双精度(或浮点数)是否是 C++ 中的 NaN 在 C++ 中使用 NaN?http://bytes.com/topic/c/answers/588254-how-check-double-inf-nan