我在这部分代码中遇到了 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 center_x(在第一次通过循环中确定然后是 nan),pos_x,center_y(在第一次通过循环中确定然后是 nan),pos_y,方向。right_rad=0。显然问题出在“其他”部分。
好的,缩小到这一行:float right_rad=width/(vel_left/vel_right-1); 由于某种原因,结果为 0。
问题解决了。非常感谢你们。