代码在循环内不起作用,但在循环外起作用
Code doesn't work inside a loop but works outside the loop
我有一段代码显示出一些奇怪的行为。当代码被排除在 for 循环之外时,它按预期工作,但是一旦我将它放在 for 循环中,它就会一次又一次地重复相同的值。
const double *north = cp->getValues();
angle1 = atan2(north[1], north[2]);
bearing = (angle1 - 1.5708) / M_PI * 180.0;
std::cout<<"Bearing inside : "<<bearing<<std::endl;
if (bearing < 0.0)
bearing = bearing + 360.0;
t = abs(bearing - turn);
这部分代码应该在每次对象旋转时更新 *north。每当我将这段代码放在循环之外时,就会发生这种情况。但是一旦代码保存在 for 循环中,如下所示,*north 的值保持不变。
for(int i=0;i<100;i++)
{
double t_modifier = (180.0 - abs(t)) / 180.0;
double threshold = 2.0;
double Speedleft = 1.0;
double Speedright = 1.0;
int identifier;
if(int(t)<0){
Speedleft = -1;
}
else if(int(t)>0){
Speedright = -1;
}
leftSpeed = threshold * Speedleft;
rightSpeed = threshold * Speedright;
{
wheels[0]->setVelocity(leftSpeed);
wheels[1]->setVelocity(rightSpeed);
wheels[2]->setVelocity(leftSpeed);
wheels[3]->setVelocity(rightSpeed);
}
const double *north = cp->getValues();
angle1 = atan2(north[1], north[2]);
bearing = (angle1 - 1.5708) / M_PI * 180.0;
std::cout<<"Bearing inside : "<<bearing<<std::endl;
if (bearing < 0.0)
bearing = bearing + 360.0;
t = abs(bearing - turn);
}
我有一段代码显示出一些奇怪的行为。当代码被排除在 for 循环之外时,它按预期工作,但是一旦我将它放在 for 循环中,它就会一次又一次地重复相同的值。
const double *north = cp->getValues();
angle1 = atan2(north[1], north[2]);
bearing = (angle1 - 1.5708) / M_PI * 180.0;
std::cout<<"Bearing inside : "<<bearing<<std::endl;
if (bearing < 0.0)
bearing = bearing + 360.0;
t = abs(bearing - turn);
这部分代码应该在每次对象旋转时更新 *north。每当我将这段代码放在循环之外时,就会发生这种情况。但是一旦代码保存在 for 循环中,如下所示,*north 的值保持不变。
for(int i=0;i<100;i++)
{
double t_modifier = (180.0 - abs(t)) / 180.0;
double threshold = 2.0;
double Speedleft = 1.0;
double Speedright = 1.0;
int identifier;
if(int(t)<0){
Speedleft = -1;
}
else if(int(t)>0){
Speedright = -1;
}
leftSpeed = threshold * Speedleft;
rightSpeed = threshold * Speedright;
{
wheels[0]->setVelocity(leftSpeed);
wheels[1]->setVelocity(rightSpeed);
wheels[2]->setVelocity(leftSpeed);
wheels[3]->setVelocity(rightSpeed);
}
const double *north = cp->getValues();
angle1 = atan2(north[1], north[2]);
bearing = (angle1 - 1.5708) / M_PI * 180.0;
std::cout<<"Bearing inside : "<<bearing<<std::endl;
if (bearing < 0.0)
bearing = bearing + 360.0;
t = abs(bearing - turn);
}