在C++中检查double(或float)是否是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

更新于:30-Jul-2019

13K+浏览

开启你的事业

完成课程获得认证

开始
广告
© . All rights reserved.