查找NaN错误的原因
Finding the cause of NaN error
我在这段代码中遇到了一个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
变量的共同因素。如果你对一个尚未初始化的变量执行sin
或cos
,或者是无穷大或NaN,你会得到NaN。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- g++的分段错误(在NaN上使用to_string两次时)
- 调用某个回调函数两次会导致分段错误:Nan
- 插件中节点.js/Nan 回调C++不频繁的隔离错误
- 运行代码时出现 NaN 错误
- C++:在数学错误中创建实际错误而不是 NAN
- 查找NaN错误的原因