C++ 查找NaN错误的原因

C++ 查找NaN错误的原因,c++,nan,C++,Nan,我在这段代码中遇到了一个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

我在这段代码中遇到了一个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;
}
void Robot::updatePos(int-msTime){
如果(左电平==右电平){
pos_x-=vel_right*msTime*0.001*sin(方向);
pos_y-=vel_right*msTime*0.001*cos(方向);
}
否则{
int符号=1;

如果(vel_left如果
right_rad
=0,则您将在此处除以零:

orientation+=sign*vel_right*msTime/right_rad;

除此之外,我看不出你会得到NaN的任何原因。

不幸的是,我没有足够的代表只留下评论,但是当你进入该函数时,
方向的值是什么?这似乎是所有变量的共同因素,这些变量是
NaN
。如果你执行
sin
cos
对于一个尚未初始化的变量,或者是无穷大或NaN,您将返回NaN。

对不起,应该已经指定了。函数在循环中运行)我为以下变量获取NaN centre_x(在第一个通过循环中ok然后NaN),pos_x,centre_y(在第一个通过循环中ok然后NaN),pos_y,orientation.right_rad=0当您除以0时,请参见下面我的答案。如果问题已解决,请添加[已解决]在标题前加前缀,并投票选择下面的某个答案,并将其选作答案。使用值0vel_left==0和vel_right==1初始化方向不会导致除以零,因为表达式的计算结果为
((vel_left/vel_right)-1)
,而不是
(vel_left/(vel_right-1))
。vel_left等于vel_right(或者非常接近,四舍五入后的商是1)导致除法为零。啊,我误读了。你是对的。现在修复了它。