I want to rotate a point around the origin but I keep getting errors. The mathematical part is solid but the code seems to fail when I want it to update the x and y values from the specific points. Can you guys help me?
Kind regards, Vincent
#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
}
Solved! Thx for your help guys. You can find the new code below:
#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
}
A few issues in the code. You are returning Point(x, y) on roa() while the function returns a double which makes it unable to compile. If you want to rotate the same point, you are already setting x and y values in roa(), no need to reassign the whole variable at a = a.roa(50)
. Just do a.roa()
with roa() modified as follows:
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;
}
Finally, as bialy pointed out, the angle should be in radians not degrees!
Documentation says that angle is in radians: http://www.cplusplus.com/reference/cmath/cos/
To convert angles to radians just
double angle_radians = angle_degrees / (180.0 / M_PI);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.