Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define NaN value in ANSI C? [duplicate]

Possible Duplicate:
NaN Literal in C?

I'm writing a function in ANSI C which receives two numbers as parameters. The parameters are of int or float type. The number may or may not be valid according to my filter. How do I return some value meaning failure? The return type is float. The first thing that come to my mind was the NaN abstract type. But I don't know how to represent it in ANSI C.

(sorry for my bad english. English isn't my native language)

like image 613
Jack Avatar asked Jan 05 '13 18:01

Jack


People also ask

How do you code NaN?

One way to check for NaN would be: #include <math. h> if (isnan(a)) { ... } You can also do: a !=

How is NaN represented in C?

Using floating point numbers, 0.0 / 0.0 isn't a "divide by zero" error; it results in NaN . In terms what NaN looks like to the computer, two "invalid" numbers are reserved for "signaling" and "quiet" NaN (similar to the two invalid numbers reserved for positive and negative infinity).

Does NaN exist in C?

NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions).

How do I know if my float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.


1 Answers

NaN isn't an "abstract type". It's a value of a floating-point datum.

If by "ANSI C" you mean standard C (which is the actual meaning of the term, in as much as it has one), include <math.h> and use the NAN macro to produce a nan, and isnan(x) to detect one.

If by "ANSI C" you actually mean the long-replaced C89 standard (which some people intend, even if it isn't formally correct), you can produce a NaN value with 0./0., and check for one with x != x.

like image 169
Stephen Canon Avatar answered Sep 23 '22 06:09

Stephen Canon