Objective-C - nan 的浮点检查
我有一个变量浮动斜率
,在打印时有时会具有nan
值,因为有时会发生除以0
的情况。
我正在尝试在发生这种情况时执行 if-else。我怎样才能做到这一点? if (slope == nan)
似乎不起作用。
I have a variable float slope
that sometimes will have a value of nan
when printed out since a division by0
sometimes happens.
I am trying to do an if-else for when that happens. How can I do that? if (slope == nan)
doesn't seem to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两种方式或多或少是等效的:
或者
(
man isnan
将为您提供更多信息,或者您可以在 C 标准中阅读所有相关信息)或者,您可以在之前检测到分母为零你进行除法(或者使用
atan2
,如果你最终只是在斜率上使用atan
而不是进行一些其他计算)。Two ways, which are more or less equivalent:
Or
(
man isnan
will give you more information, or you can read all about it in the C standard)Alternatively, you could detect that the denominator is zero before you do the divide (or use
atan2
if you're just going to end up usingatan
on the slope instead of doing some other computation).没有什么东西等于
NaN
— 包括NaN
本身。所以检查x != x
。Nothing is equal to
NaN
— includingNaN
itself. So checkx != x
.希望这对你有用。
Hope this will work for you.
在 Swift 中,您需要执行
slope.isNaN
来检查它是否为 NaN。In Swift, you need to do
slope.isNaN
to check whether it is a NaN.