什么是 NaN?以及是如何创建的?
我有一个 double[]
,它的值为 NaN
。当我将数组的元素相加时,NaN
也使结果为 NaN
。
它是怎么发生的?如何防止此 NaN
添加到数组的其余部分?
I have a double[]
and it has a value which is NaN
. When I add up the array's elements, the NaN
makes the result NaN
too.
How did it happen? How can I prevent this NaN
from being added to the rest of my array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
NaN
代表非数字。它可以以多种方式出现,例如由于0 ./0.
、sqrt(-1)
,或作为涉及其他NaN
的计算结果。检查
v
是否为NaN
的最简单方法是使用Double.isNaN(v)
:编辑: @Stephen C在评论中提出了一个很好的观点:在决定忽略该
NaN
之前,明智的做法是了解它的来源。这可能是代码中其他地方的错误造成的,如果盲目地忽略NaN
,您可能只是掩盖了该错误而不是修复它。NaN
stands for Not-a-Number. It can arise in a variety of ways, for example as a result of0./0.
,sqrt(-1)
, or as the result of a calculation involving otherNaNs
.The easiest way to check whether
v
is aNaN
is by usingDouble.isNaN(v)
:edit: @Stephen C makes a good point in the comments: before deciding to ignore that
NaN
, it would be prudent to understand where it came from. It could be that it is the result of a bug elsewhere in your code, and by blindly ignoring theNaN
you could simply be masking the bug instead of fixing it.NaN 代表“Not a Number”,因此“Not A Number”+ 10 =“Not a Number”
您可能需要考虑调试您的应用程序以查找双数组中的内容:)
NaN stands for "Not a Number", so "Not A Number" + 10 = "Not a Number"
You might want to consider debuggin your app to find what's in the double array :)
这样:
This way:
RTFM:
NaN 的 Javadoc
JVM 规范的相关部分说任何涉及
NaN
的操作也是NaN
(有点像 SQL 中的null
)RTFM:
Javadoc for NaN
And relevant section of the JVM spec says any operation involving a
NaN
is also aNaN
(a bit like anull
in SQL)你不能忽略 NaN,它表明你的程序有问题。您需要找出导致 NaN 的原因并修复它。
You can't just ignore the NaN, it's an indicator of a problem with you're program. You need to find out what is causing the NaN and fix that.
NaN - 不是数字
顺便尝试一下:
NaN - Not a Number
btw try :
Java 不是我的强项,但在其他语言中,这来自于从字符串中分配值。试试这个:
parseDouble
返回一个新的 double,初始化为指定 String 表示的值,如 Double 类的 valueOf 方法执行的那样。
参数:
s - 要解析的字符串。
返回:
由字符串参数表示的双精度值。
投掷:
NumberFormatException - 如果字符串不包含可解析的双精度值。
自从:
1.2
参见:
valueOf(String)
取自此处。
Java isn't my strong suit, but in other languages this comes from assigning a value from a string. Try this:
parseDouble
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Parameters:
s - the string to be parsed.
Returns:
the double value represented by the string argument.
Throws:
NumberFormatException - if the string does not contain a parsable double.
Since:
1.2
See Also:
valueOf(String)
Taken from here.