如何在C中使用nan和inf? [英] How to use nan and inf in C?

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

问题描述

我有一个数值方法,可以在出现错误时返回 nan 或 inf,为了测试目的,我想暂时强制它返回 nan 或 inf 以确保正确处理情况.是否有一种可靠的、独立于编译器的方法来在 C 中创建 nan 和 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?

在谷歌搜索大约 10 分钟后,我只能找到依赖于编译器的解决方案.

After googling for about 10 minutes I've only been able to find compiler 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 类型的常量表达式无穷大,如果有的话;else 为在翻译时溢出的 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 可以定义也可以不定义,并且当且仅当实现支持 float 类型的安静 NaN 时才定义.它扩展为表示安静 NaN 的 float 类型的常量表达式."

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()C99 中 math.h 中的宏.

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

C99 也有 nan 功能:

C99 also has nan functions:

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

(参考:n1256).

(Reference: n1256).

文档无限文档 NAN

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

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