Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Checking if a double (or float) is NaN in C++
In this article we will check whether a double or floating point number is NaN (Not a Number) in C++.
Checking if a Double or Floating Point Number is NaN
To check, we can utilise the isnan() method. The isnan() function is available in the cmath library. This function was introduced in C++ version 11. So From C++11 next, we can use this function.
The isnan() function is used to determine whether a double or floating point number is not-a-number (NaN) value. Return true if num is NaN, false otherwise.
C++ Program to Check Double or Float Number is NaN
In the following example, we are checking a floating point and double number is NaN using the isnan() function in C++:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Produces NaN
float floatValue = sqrt(-1.0f);
// Also produces NaN
double doubleValue = 0.0 / 0.0;
// Check float
if (isnan(floatValue)) {
cout << "floatValue is NaN." << endl;
} else {
cout << "floatValue is valid." << endl;
}
// Check double
if (isnan(doubleValue)) {
cout << "doubleValue is NaN." << endl;
} else {
cout << "doubleValue is valid." << endl;
}
return 0;
}
Following is the output:
floatValue is NaN. doubleValue is NaN.
Advertisements
