C++ cmath nan() Function
Example
Create a NaN value, and check it with isnan():
double x = nan("");
if (isnan(x)) {
cout << "x is NaN (Not a Number)";
}
Definition and Usage
The nan() function returns a special double value called NaN, which means "Not a Number". It is often used to show that a calculation has no valid result.
NaN is not equal to any value, not even itself. So you cannot check for it with ==. Use isnan() instead, like in the example.
The nan function is defined in the <cmath> header file.
Note: When you print a NaN value with cout, the text can be different between compilers, like nan or -nan. This is why the example uses isnan().
Syntax
nan(const char* s)
Use nanf() to get a float NaN, and nanl() to get a long double NaN.
Parameter Values
| Parameter | Description |
|---|---|
| s | Required. A text (a C-style string). Some compilers use it to choose how the NaN is stored inside. In most cases, use an empty string: "". |
Technical Details
| Returns: | A double NaN value. |
|---|
Related Pages
Read more about math in our Math Tutorial.