#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
int main ()
{
float xstart = -2, xfinal = 2, h = 0.5;
float t, y;
cout << "X start = -2" << endl;
cout << "X final = 2" << endl;
cout << "step = 0.5" << endl << endl;
for ( float x = xstart; x <= xfinal; x+= h)
{
t= sqrt(pow(sin(x),2)) / sqrt(x - 4);
y= sqrt(2 * t + x);
cout << x << " | " << t << " | " << y << endl;
}
cout << endl;
}
这会将 t 和 y 变量输出为 nan。我不知道如何修复它。该代码只是问题的示例,除了修复 nans 之外无需执行任何其他操作。
最佳答案
t= sqrt(pow(sin(x),2)) / sqrt(x - 4);
在 C++ 中,负数的平方根被定义为 NAN,“不是数字”。由于变量 x
在 [-2, 2]
范围内迭代,你永远不会让它不是 NAN,这意味着使用它的所有计算都将到达南。
如果您希望 sqrt 返回复数,则需要使用 std::complex
及其各种数学函数。
关于c++ - 面向初学者的 C++ 中的 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40537325/