如何使用楠用C INF? [英] How to use nan and inf in C?

查看:124
本文介绍了如何使用楠用C INF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数值方法,可以返回NaN或INF,如果有错误,并进行测试意,我想暂时迫使它返回NaN或INF,以确保局面正在得到正确处理。有没有一种可靠的,的编译器无关的方式C创建楠的价值观和INF?

I have a numerical method that could return nan or inf if there was an error, and for testing purposed I'd like to temporarily force it to return nan or inf to ensure the situation is being handled correctly. Is there a reliable, compiler-independent way to create values of nan and inf in C?

google搜索约10分钟后,我只能够找到编译依赖的解决方案。

After googling for about 10 minutes I've only been able to find complier dependent solutions.

推荐答案

您可以测试您的实现了它:

You can test if your implementation has it:

#include <math.h>
#ifdef NAN
/* NAN is supported */
#endif
#ifdef INFINITY
/* INFINITY is supported */
#endif

INFINITY的存在是由C99保证(或最新草案至少),以及扩展到float类型重新$ p的不断前pression $ psenting正面或签名
无穷大,如果有的话;别的float类型的溢出在转换时的正数。

The existence of INFINITY is guaranteed by C99 (or the latest draft at least), and "expands to a constant expression of type float representing positive or unsigned infinity, if available; else to a positive constant of type float that overflows at translation time."

NAN 可以或可以不被定义,并且被定义当​​且仅当实现支持浮子式提示NaN它膨胀到恒定前$ P pssion $ float类型重新presenting静态NaN的。

NAN may or may not be defined, and "is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN."

请注意,如果你是比较浮点值,然后执行:

Note that if you're comparing floating point values, and do:

a = NAN;

即使是这样,

a == NAN;

是假的。检查NaN的一种方法将是:

is false. One way to check for NaN would be:

#include <math.h>
if (isnan(a)) { ... }

您也可以做到! A = A 来测试,如果 A 是NaN

You can also do: a != a to test if a is NaN.

还有 ISFINITE() isinf() isnormal() signbit()文件math.h 在C99。

There is also isfinite(), isinf(), isnormal(), and signbit() macros in math.h in C99.

C99还具有功能:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(ocnst char *tagp);

(参考:n1256)。

(Reference: n1256).

这篇关于如何使用楠用C INF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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