我想绕原点旋转一个点,但我不断出错。数学部分是可靠的,但是当我希望它从特定点更新x和y值时,代码似乎失败了。你们能帮我吗?

亲切的问候,
文森特


#include <cmath>
#include <iostream>
#include <iomanip>


class Point
{
public:

    double x, y;
    // constructors

    Point()
        : x(0), y(0)
    {}

    Point(double X, double Y)
        : x(X), y(Y)
    {}

    double roa(double angle)
    {
        double new_x = x*cos(angle) - y*sin(angle);
        double new_y = x*sin(angle) + y*sin(angle);
        x = new_x;
        y = new_y;

        return Point(x,y);
    }
};

int main()
{
    Point a(2,2);
    a = a.roa(50);
    std::cout << a << std::endl;

    return 0
}

解决了!谢谢您的帮助。您可以在下面找到新代码:

#include <cmath>
#include <iostream>
#include <iomanip>


class Point
{
public:

    double x, y;
    // constructors

    Point()
        : x(0), y(0)
    {}

    Point(double X, double Y)
        : x(X), y(Y)
    {}

    Point roa(double angle)
    {
        double angle_rad = angle / (180/M_PI);

        double new_x = x*cos(angle_rad) - y*sin(angle_rad);
        double new_y = x*sin(angle_rad) + y*cos(angle_rad);

        double x = new_x;
        double y = new_y;

        Point p;
        p.x = new_x;
        p.y = new_y;

        return p;

    }
};

int main()
{
    Point a(2,2);
    a = a.roa(360);
    std::cout << a << std::endl;

    return 0
}


最佳答案

代码中的一些问题。您在roa()上返回Point(x,y),而函数返回一个double值,这使其无法编译。如果要旋转同一点,则已经在roa()中设置了x和y值,无需在a = a.roa(50)处重新分配整个变量。只需使用roa()进行a.roa()修改,如下所示:

void roa(double angle)
{
  double new_x = x*cos(angle) - y*sin(angle);
  double new_y = x*sin(angle) + y*cos(angle); // mistake here as well
  x = new_x;
  y = new_y;
}

最后,正如偏心指出的那样, Angular 应为弧度而不是度!

10-07 13:42