C++中的楠——它是什么以及如何检查它?

NaN是 不是数字 是一个异常,通常发生在表达式生成的数字为 未定义 无法代表 。它用于浮点运算。例如:

null
  • 负数的平方根
  • 除零
  • 取0或负数等的对数。

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;
}


输出

1.41421-nan

如何在C++中检查楠?

方法1:使用 比较(“=”)运算符 .

在这种方法中,我们通过比较一个数字本身来检查它是否复杂。如果结果为真,则数字为 复杂的,即真实的。但如果结果为false,则返回“nan”,即数字为复数。

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;
}


输出

Its a real numberIts NaN

方法2:使用内置函数“isnan()

检查NaN的另一种方法是使用“isnan()”函数,如果一个数字很复杂,该函数将返回true,否则将返回false。这个C库函数出现在 头文件。

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;
}


输出

Its a real numberIts NaN

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享