When does NaN occur?
NaN occurs when there is a run-time error, it can happen when
- A number is divided by zero.
- Finding log of a negative number.
- Finding the square root of a negative number.
Example:
#include <iostream>
#include<math.h>
int main()
{
int a = 25;
int b = -35;
std::cout<<sqrt(a)<<std::endl;
std::cout<<sqrt(b);
return 0;
}
Output:
5
-nan
As you can see, mathematically, the square root of a negative number cannot be calculated. Therefore, the compiler gave NaN.
Inbuilt NaN function
#include <iostream>
#include<math.h>
int main()
{
int a = 400;
int b = -100;
if (std::isnan(sqrt(a)))
std::cout<<"\nIt is a NaN";
else
std::cout<<"\nIt is a real number";
if (std::isnan(sqrt(b)))
std::cout<<"\nIt is a Nan";
else
std::cout<<"\nIt is a real number";
return 0;
}
Output:
It is a real number
It is a Nan
Try and compile with online c++ compiler
Types of NaN
There are basically three return types of NaN.
nanf(): It consists of float type of NaN.
nan(): It consists of double type of NaN.
nanl(): It consists of long double type of NaN.
Also check out this article - Pair in C++
Must Read Swap Two Numbers Without Using Third Variable, Fibonacci Series in C++
FAQs
-
Why does the NaN exist?
NaN occurs because, in programming, it is neither an error nor an exception but a value that is assigned.
-
How to remove NaN?
NaN can be removed with the help of the inbuilt isnan() function. The programmer can check the NaN value before executing the code.
-
How is NaN a number?
By definition, NaN is the returned value from the undefined numerical values operations.
-
What are the types of NaN?
NaN is of two kinds; quiet NaN and Signalling NaN. The difference between the two is that signaling NaN will cause an exception when used in arithmetic operations, and quiet NaN will not.
Key Takeaways
In this article, we have extensively discussed NaN, its implementation in C++, and its types. We hope that this blog has helped you enhance your knowledge regarding NaN and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!