NaN in C++ – What is it and How to Check For it?
Last Updated :
06 Feb, 2023
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
- Division by zero
- Taking the log of zero or a negative number etc.
CPP
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
float a = 2, b = -2;
cout << sqrt (a) << endl;
cout << sqrt (b) << endl;
return 0;
}
|
Time Complexity: O(1)
Space Complexity: O(1)
How to check for NaN in C++?
Method 1: Using compare (“==”) operator.
In this method, we check if a number is complex by comparing it with itself. If the result is true, then the number is not complex i.e., real. But if the result is false, then “nan” is returned, i.e. the number is complex.
CPP
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
float a = sqrt (2);
float b = sqrt (-2);
a == a ? cout << "Its a real number" << endl
: cout << "Its NaN" << endl;
b == b ? cout << "Its a real number" << endl
: cout << "Its NaN" << endl;
return 0;
}
|
Output
Its a real number
Its NaN
Time Complexity: O(1)
Space Complexity: O(1)
Method 2: Using inbuilt function “isnan()”
Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file.
CPP
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
float a = sqrt (2);
float b = sqrt (-2);
isnan(a) ? cout << "Its NaN" << endl
: cout << "Its a real number" << endl;
isnan(b) ? cout << "Its NaN" << endl
: cout << "Its a real number" << endl;
return 0;
}
|
Output
Its a real number
Its NaN
Time Complexity: O(1)
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...