c++初学者的Nan

nan in c++ for beginner

本文关键字:Nan 初学者 c++      更新时间:2023-10-16
#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。我不知道如何修理它。这段代码只是问题的一个例子,不需要做任何其他的事情,除了修复nan。

t= sqrt(pow(sin(x),2)) / sqrt(x - 4);

在c++中,负数的平方根被定义为NAN (Not a number)。因为变量x在范围[-2, 2]中迭代,所以你永远不会让它不是NAN,这意味着使用它的所有计算都将到达NAN。

如果你希望sqrt返回复数,你需要使用std::complex和它的各种数学函数

只要您继续在sqrt函数中使用负数,它就无法修复。(提示:x - 4总是负值或零)