Objective-C-浮点数检查nan [英] Objective-C - float checking for nan

查看:88
本文介绍了Objective-C-浮点数检查nan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量(float slope),由于有时会被0除,因此在打印时有时会具有nan值.

I have a variable (float slope) that sometimes will have a value of nan when printed out since a division by 0 sometimes happens.

我正在尝试在发生这种情况时进行if-else操作.我怎样才能做到这一点? if (slope == nan)似乎不起作用.

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.

推荐答案

两种方法,或多或少等效:

Two ways, which are more or less equivalent:

if (slope != slope) {
    // handle nan here
}

#include <math.h>
...
if (isnan(slope)) {
    // handle nan here
}

(man isnan将为您提供更多信息,或者您可以在C标准中阅读所有信息)

(man isnan will give you more information, or you can read all about it in the C standard)

或者,您可以在进行除法之前检测到分母为零(或者,如果要在斜率上最终使用atan而不是进行其他一些计算,请使用atan2).

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 using atan on the slope instead of doing some other computation).

这篇关于Objective-C-浮点数检查nan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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