c++ - 在cpp中围绕原点旋转一个点?

标签 c++ class rotation parameter-passing

我想围绕原点旋转一个点,但我总是出错。数学部分是可靠的,但是当我希望它从特定点更新 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) 重新分配整个变量。只需将 a.roa() 修改为 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;
}

最后,正如 bialy 所指出的,角度应该以弧度而不是度为单位!

关于c++ - 在cpp中围绕原点旋转一个点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076207/

相关文章:

css - 向没有类或id的div添加属性值?

iphone - 在网格上旋转 CGPoint 的最佳方法是什么?

c++ - 如何使用 GetProfileSectionA 读取 C++ 中的 INI 部分

c++ - 为什么不同的编译器生成不同大小的文件?

ios - 如何从子项目中包含一个类

python - 打印带条件的二次方程

JavaScript/jQuery : How to get actual original position of an element (DIV) after it's been rotated

javascript - 如何在鼠标移动事件后围绕其中心旋转 Canvas 对象?

c++ - 王牌 (C++) : Not calling cancel_timer == MLK?

c++ - Irrlicht 引擎 : code commenting convention?