查找NaN错误的原因

Finding the cause of NaN error

本文关键字:错误 NaN 查找      更新时间:2023-10-16

我在这段代码中遇到了一个NaN错误:

void Robot::updatePos(int msTime){
    if(vel_left==vel_right){
        pos_x-=vel_right*msTime*0.001*sin(orientation);
        pos_y-=vel_right*msTime*0.001*cos(orientation);
    }
    else{
        int sign=1;
        if(vel_left<vel_right) sign=-1;
        float centre_x, centre_y;
        float right_rad=width/(vel_left/vel_right-1);
        centre_x=pos_x-cos(orientation)*(right_rad+width/2);
        centre_y=pos_y-sin(orientation)*(right_rad+width/2);
        cout << "centre" << centre_x << "right_rad" << right_rad << endl;
        orientation+=sign*vel_right*msTime/right_rad;

        pos_x=centre_x+cos(orientation)*(right_rad+width/2);
        pos_y=centre_y+sin(orientation)*(right_rad+width/2);
    }
    while(orientation>M_PI) orientation-=2*M_PI;
    while(orientation<-M_PI) orientation+=2*M_PI;
    cout << "pos_x: " << pos_x << " pos_y: " << pos_y <<
                " orientation: " << orientation << endl;
}

所有的类变量都是浮动的。你知道是什么原因导致了这个错误吗?

编辑:对不起,应该指定的。函数在循环中运行)我得到以下变量的NaN centre_x(在第一次通过循环中ok然后NaN),pos_x,centre_y(在第一个通过循环中ok然后NaN,pos_y,orientation。right_rad=0。显然问题出在"else"部分。

好,缩小到以下行:float right_rad=宽度/(vel_left/vel_right-1);由于某种原因,结果是0。

问题解决了。非常感谢各位。

如果right_rad=0,那么您将在此处被零除:

orientation+=sign*vel_right*msTime/right_rad;

除此之外,我看不出你为什么会得到NaN。

不幸的是,我没有足够的rep来留下评论,但当您输入该函数时,orientation的值是多少?这似乎是所有NaN变量的共同因素。如果你对一个尚未初始化的变量执行sincos,或者是无穷大或NaN,你会得到NaN。