float f = (float)'a'; if(f < 0){ } else if(f == 0){ } else if(f > 0){ } else{ printf("NaN\n"); }
f
won't be greater/equal/less than 0
if it's a NaN
.
But how to produce such a f
in the first place?
I tried various ways to produce a NaN
,but none work..
In computing, NaN (/næn/), standing for Not a Number, is a member of a numeric data type that can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic.
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).
NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.
Checking if a double (or float) is NaN in C++ 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.
Using floating point numbers, 0.0 / 0.0
isn't a "divide by zero" error; it results in NaN
.
This C program prints -nan
:
#include <stdio.h> int main() { float x = 0.0 / 0.0; printf("%f\n", x); return 0; }
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). The Wikipedia entry has more details about how NaN is represented as an IEE floating point number.
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