How to check if a float is NaN in C++

2 Answers

0 votes
#include <iostream>
#include <cmath> // For std::isnan

int main() {
    float f = std::nanf(""); 

    if (std::isnan(f)) {
        std::cout << "The value is NaN." << std::endl;
    } else {
        std::cout << "The value is not NaN." << std::endl;
    }
}

 
 
/*
run:
 
The value is NaN.
 
*/
   
 

 



answered May 11, 2025 by avibootz
edited May 11, 2025 by avibootz
0 votes
#include <iostream>
#include <cmath> // For std::isnan

int main() {
    float f = std::nanf(""); 

    if (f != f) {
        std::cout << "The value is NaN." << std::endl;
    } else {
        std::cout << "The value is not NaN." << std::endl;
    }
}

 
 
/*
run:
 
The value is NaN.
 
*/
   
 

 



answered May 11, 2025 by avibootz

Related questions

...