Home » C++ programming language

nan() function with example in C++

C++ nan() function: Here, we are going to learn about the nan() function with example of cmath header in C++ programming language?
Submitted by IncludeHelp, on April 28, 2019

C++ nan() function

nan() function is a library function of cmath header, it is used to get the NaN value, it returns a quiet NaN (Not-A-Number) value of double type.

Syntax of nan() function:

    nan(const char* tagp);

Parameter(s): const char* tagp – an implementation-specific C-String, it can be an empty string ("") to generate a generic NaNvalue (nan).

Return value: double – returns the NaN value (nan) of type double.

Example:

    Function call:
    nan("");    
    
    Output:
    nan

C++ code to demonstrate the example of nan() function

// C++ code to demonstrate the example of 
// nan() function

#include <iostream>
#include <cmath>
using namespace std;

// main() section
int main()
{
    double nanValue;
    
    //generating generic NaN value
    //by passing an empty string
    nanValue = nan("");
    
    //printing the value 
    cout<<"nanValue: "<<nanValue<<endl;
    
    return 0;
}

Output

nanValue: nan

Example to print the type of NaN ("nan")

In C++, to print the type of a variable or value, we can use typeid() by passing the variable name or the value and the function name() with the statement typeid(variable/value) returns the type of the variable. To use these functions, we must use typeinfo header.

Consider this example,

// C++ code to demonstrate the example of 
// nan() function & printing the return type of nan()

#include <iostream>
#include <cmath>
#include <typeinfo>     //for types related functions
using namespace std;

// main() section
int main()
{
    double nanValue;
    
    //generating generic NaN value
    //by passing an empty string
    nanValue = nan("");
    
    //printing the value 
    cout<<"nanValue: "<<nanValue<<endl;
    
    //printing the type of nan
    cout<<"type of nan: "<<typeid(nanValue).name()<<endl;
    
    return 0;
}

Output

nanValue: nan
type of nan: d

See the output – type of nan is d that is used for the double.

Reference: C++ nan() function



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.