我的代码使用公式来查找我的机器人声纳传感器发现障碍物的位置。 代码如下所示:
obstacleX = robot.x + robot.sensorReadings.at(i) * cos((robot.deg + i * angleBetweenSensors) * PI / 180);
obstacleY = robot.y + robot.sensorReadings.at(i) * sin((robot.deg + i * angleBetweenSensors) * PI / 180);
而且我想让它成为一个函数,不要多次重复这个公式(并且让它更容易改变)。我会做这样的功能:
double calculateObstaclePosition(double robotX, double sesnorReading, double robotDegree, int angleBetweenSensors){
return robotX + sesnorReading * cos((robotDegree + i * angleBetweenSensors) * PI / 180);
}
然后路过
obstacleX = calculateObstaclePosition(robot.x, robot.sensorReadings.at(i), robot.deg, angleBetweenSensors);
但是X和Y的公式几乎是一样的,唯一的区别是一个用sinus,一个用cosinus。然后我应该创建两个几乎相同的函数还是可以在一个函数中完成?
最佳答案
可用选项:
(1)用一个flag来表示是要用cosine还是sine:
double calculateObstaclePosition(double robotC, ..., bool useCos)
{
double angle = (robotDegree + i * angleBetweenSensors) * PI / 180;
return robotC + sensorReading * (useCos ? cos(angle) : sin(angle));
}
(2) 创建一些二维 vector 数据类型并一次性返回两个坐标
struct vec2D
{
double x, y;
};
vec2D calculateObstaclePosition(double robotX, double robotY, ...)
{
vec2D pos;
double angle = (robotDegree + i * angleBetweenSensors) * PI / 180;
pos.x = robotX + sensorReadingX * cos(angle);
pos.y = robotY + sensorReadingY * sin(angle);
return pos;
}
或者使用类什么的。也可以将机器人类转换为使用 vec2D 作为坐标。
(3) 晦涩一:传递一个数值函数的指针给want。不安全!!!
typedef double (*numfuncptr)(double a);
double calculateObstaclePosition(double robotC, ..., numfuncptr trig)
{
double angle = ...;
return robotC + sensorReading * trig(angle);
}
(4) 不是那么晦涩,而是 C 风格,因此不是 OOP 风格:传递变量的输出指针。 (再次不安全)
void calculateObstaclePosition(double robotX, double robotY, ..., double* outX, double* outY)
{
double angle = ...;
*outX = robotX + ...
*outY = robotY + ...;
}
关于c++ - 如何将此公式拆分为 C++ 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35831233/