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)
One way to check for NaN would be: #include <math. h> if (isnan(a)) { ... } You can also do: a !=
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).
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).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With