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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:50:45  来源:igfitidea点击:

check NaN number

c++numbers

提问by MBZ

Is it possible to check if a number is NaNor not?

是否可以检查一个数字是否NaN存在?

回答by paxdiablo

Yes, by use of the fact that a NaNis not equal to any other number, including itself.

是的,通过使用 aNaN不等于任何其他数字(包括其自身)这一事实

That makes sense when you think about what NaNmeans, 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.hfor C and cmathfor C++) or just use the property that a NaNvalue is not equal to itself with something like:

您可以寻找一个函数(实际上是宏)isnan(在math.hC 和cmathC++ 中),或者只是使用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

回答by Scott M.

you are looking for null, but that is only useful for pointers. a number can't be null itself, it either has a known value that you put in there or random data from whatever was there in memory before.

您正在寻找null,但这仅对指针有用。数字本身不能为空,它要么具有您放入其中的已知值,要么具有来自之前内存中任何内容的随机数据。