isnormal() function in C++
In this tutorial, we are going to talk about the working of the isnormal() function in C++. As it is very much evident from its name, this function is used to find out whether a number is normal or not. A number is not normal if it is zero, infinite or NAN. Otherwise, the number is normal.
isnormal() function: Syntax and working
The isnormal() function() is defined in <cmath> header of C++. Its syntax would be like this.
bool isnormal(float num); bool isnormal(double num); bool isnormal(long double num);
As you can see, the function takes a floating-point value as an argument and returns a boolean value- 1(true) or 0(false). Let’s see more on this with example programs.
#include <iostream> #include <cmath> int main() { float num = 5.0F; std::cout << num << " is " << (std::isnormal(num)? "normal" : "not normal" ) << std::endl; num = 0.0F; std::cout << num << " is " << (std::isnormal(num)? "normal" : "not normal") << std::endl; num = 5.0F / 0.0F; std::cout << num << " is " << (std::isnormal(num)? "normal" : "not normal") << std::endl; return 0; }
The above C++ program gives the output:
5 is normal 0 is not normal inf is not normal
Here, have a look at another example when arguments are passed as double.
#include <iostream> #include <cmath> int main() { double num = 5.0; std::cout << num << " is " << (std::isnormal(num)? "normal" : "not normal" ) << std::endl; num = 0.0; std::cout << num << " is " << (std::isnormal(num)? "normal" : "not normal") << std::endl; num = 5.0 / 0.0; std::cout << num << " is " << (std::isnormal(num)? "normal" : "not normal") << std::endl; return 0; }
Output:
5 is normal 0 is not normal inf is not normal
In both of the above C++ programs, we have used isnormal() function to check whether the number passed as argument is normal or not. We have used a conditional operator in our program which prints “normal” if the function returns true otherwise it prints “not normal”. To understand the working of conditional operator see this article: Ternary Operator in C++
We can use isnormal() function with long double numbers as well.
Thank you.
Leave a Reply