NaN in C++ - What is it and How to Check For it? - GeeksforGeeks (2024)

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

// C++ code to demonstrate NaN exception

#include <cmath>

#include <iostream>

using namespace std;

// Driver Code

int main()

{

float a = 2, b = -2;

// Prints the number (1.41421)

cout << sqrt(a) << endl;

// Prints "nan" exception

// sqrt(-2) is complex number

cout << sqrt(b) << endl;

return 0;

}

Output

1.41421-nan

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

// C++ code to check for NaN exception

// using "==" operator

#include <cmath>

#include <iostream>

using namespace std;

// Driver Code

int main()

{

float a = sqrt(2);

float b = sqrt(-2);

// Returns true, a is real number

// prints "Its a real number"

a == a ? cout << "Its a real number" << endl

: cout << "Its NaN" << endl;

// Returns false, b is complex number

// prints "Its nan"

b == b ? cout << "Its a real number" << endl

: cout << "Its NaN" << endl;

return 0;

}

Output

Its a real numberIts 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

// C++ code to check for NaN exception

// using "isnan()"

#include <cmath>

#include <iostream>

using namespace std;

// Driver Code

int main()

{

float a = sqrt(2);

float b = sqrt(-2);

// Returns false as a

// is real number

isnan(a) ? cout << "Its NaN" << endl

: cout << "Its a real number" << endl;

// Returns true as b is NaN

isnan(b) ? cout << "Its NaN" << endl

: cout << "Its a real number" << endl;

return 0;

}

Output

Its a real numberIts NaN

Time Complexity: O(1)

Space Complexity: O(1)

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated : 06 Feb, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment...

NaN in C++ - What is it and How to Check For it? - GeeksforGeeks (2024)
Top Articles
Here are Top Stocks to Buy Before Union Budget 2023
72Ct ContraLuz Ethiopian Welo Rough Specimen Rough Opal
Jimmy Johns Delivery Hours
Dive Bars With Pool Tables Near Me
Gasbuddy Costco Hawthorne
Dragon's Dogma Duskmoon Tower
Lvc Final Exam Schedule
Keck Healthstream
Cristiano Ronaldo's Jersey Number: The Story Behind His No. 7 Shirt | Football News
Was bedeutet "x doubt"?
Abc Order Hs Login
Jeff Siegel Picks Santa Anita
What Is Opm1 Treas 310 Deposit
Craigslist Metal Roofing
Job Skills That Start With Y
14314 County Road 15 Holiday City Oh
The First 10 Years, Leslie Bricusse - Qobuz
Car Complaints Toyota
Loceryl NAIL LACQUER
18 Tamil Novels Pdf Free Download
Hotleak.vip
Craigslist Yamhill
Caldwell Idaho Craigslist
Used Safari Condo Alto R1723 For Sale
Auto-Mataru
Craigs List Plattsburgh Ny
Dumb Money Showtimes Near Showcase Cinema De Lux Legacy Place
Horned Stone Skull Cozy Grove
Po Box 790447 St Louis Mo 63179
Gran Turismo Showtimes Near Epic Theatres Of Ocala
Conner Westbury Funeral Home Griffin Ga Obituaries
Rugrats in Paris: The Movie | Rotten Tomatoes
Bureaustoelen & Kantoorstoelen - Kantoormeubelen | Office Centre
Best Hs Bball Players
Western Lake Erie - Lake Erie and Lake Ontario
9294027542
charleston rooms & shares - craigslist
Stony Brook Citrix Login
Grupos De Cp Telegram
Walgreens Wellington Green
My Compeat Workforce
123Movies Iron Man 2
Bfads 2022 Walmart
Depths Charm Calamity
Craigslist Nj Apartments South Jersey
Baywatch 2017 123Movies
Craigslist Sf Bay Free Stuff
Kortni Floribama Shore Drugs
Gelöst – Externe Festplatte kann nicht formatiert werden
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
2022 Basketball 247
Halloween 1978 Showtimes Near Movie Tavern Little Rock
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 6337

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.