Checking if a double (or float) is NaN in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 25-Apr-2019 19:05:14
Advertisements