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. So From C++11 next, we can use this function.

Example

#include <cmath>
#include <iostream>
using namespace std;
main() {
   if(isnan(sqrt(30))) { //square root of 30 is a floating point number
      cout << "Square root of 30 is not a number" <<endl;
   } else {
      cout << "Square root of 30 is a number" <<endl;
   }
   if(isnan(sqrt(-30))) { //square root of -30 is an imaginary number
      cout << "Square root of -30 is not a number" <<endl;
   } else {
      cout << "Square root of -30 is a number" <<endl;
   }
}

Output

Square root of 30 is a number
Square root of -30 is not a number

Updated on: 30-Jul-2019

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements