我的旋转测试功能不符合学校的。请赐教在哪里我已经错了。一直在努力解决了这么久,但无济于事。谢谢!
**********我的旋转测试**********
点(-50.000,-50.000)旋转45.000度是(0.000,0.000)
点(-6.000,-6.000)旋转45.000度是(0.000,0.000)
**********学校的旋转测试**********
点(-50.000,-50.000)旋转45.000度为(0.000,-70.711)
点(-6.000,-6.000)旋转45.000度为(0.000,-8.485)
旋转测试功能:
Point Point::operator%( double angle)
{
Point p;
double rad=angle * PI / 180.0;
double s = sin(rad);
double c = cos(rad);
// rotate point
double xnew = p.x * c - p.y * s;
double ynew = p.x * s + p.y * c;
p.x = xnew;
p.y = ynew;
return p;
// return Point(cos(degree) * (p.x) - sin(degree) * (p.y),
// sin(degree) * (p.x) - cos(degree) * (p.y));
// return p;
}
驱动程序文件:
void RotateTest(void)
{
cout << "\n********** Rotate test ********** " << endl;
Point pt1(-50, -50);
double angle = 45;
Point pt2 = pt1 % angle;
cout.setf(std::ios_base::fixed, std::ios::floatfield);
std::cout.precision(3);
cout << "Point " << pt1 << " rotated " << angle << " degrees is " <<
pt2 << endl;
pt1 = Point(-6, -6);
angle = 45;
pt2 = pt1 % angle;
cout << "Point " << pt1 << " rotated " << angle << " degrees is " <<
pt2 << endl;
cout << endl;
cout.unsetf(std::ios_base::fixed);
std::cout.precision(6);
}
list.h文件:
class Point
{
public:
// Point(double X, double Y); // Constructors (2)
explicit Point(double x, double y);
Point();
double getX() const;
double getY() const;
Point operator+(const Point& other)const ;
Point& operator+(double val) ;
Point operator*(double value) ;
Point operator%(double angle);
double operator-(const Point& other)const ;
Point operator-(double val);
Point operator^(const Point& other);
Point& operator+=(double val);
Point& operator+=(const Point& other) ;
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
Point operator-() const;
// Overloaded operators (14 member functions)
friend std::ostream &operator<<( std::ostream &output, const Point
&point );
friend std::istream &operator>>( std::istream &input, Point
&point );
// Overloaded operators (2 friend functions)
private:
double x; // The x-coordinate of a Point
double y; // The y-coordinate of a Point
// Helper functions
double DegreesToRadians(double degrees) const;
double RadiansToDegrees(double radians) const;
};
问题我从您发布的代码中看到的是,您使用的是函数的局部点,p
,用于计算变换点。据推测,其被初始化为(0,0)。旋转这一点不会改变它的位置。您需要使用this
。
Point Point::operator%( double angle)
{
Point p;
double rad=angle * PI / 180.0;
double s = sin(rad);
double c = cos(rad);
// rotate point
double xnew = this->x * c - this->y * s;
double ynew = this->x * s + this->y * c;
p.x = xnew;
p.y = ynew;
return p;
}
或简化的版本:
Point Point::operator%( double angle)
{
double rad=angle * PI / 180.0;
double s = sin(rad);
double c = cos(rad);
// rotate point
return Point(this->x * c - this->y * s,
this->x * s + this->y * c);
}