检查double(或float)在C ++中是否为NaN
要检查C++中的浮点数或双数是否为NaN(非数字),我们可以使用该isnan()函数。该isnan()函数存在于cmath库中。此函数在C++版本11中引入。因此,从C++11接下来,我们可以使用此函数。
示例
#include <cmath>
#include <iostream>
using namespace std;
main() {
if(isnan(sqrt(30))) { //square root of 30 is a floating point number
cout << "Square root of 30 is not a number" <<endl;
} else {
cout << "Square root of 30 is a number" <<endl;
}
if(isnan(sqrt(-30))) { //square root of -30 is an imaginary number
cout << "Square root of -30 is not a number" <<endl;
} else {
cout << "Square root of -30 is a number" <<endl;
}
}输出结果
Square root of 30 is a number Square root of -30 is not a number