旋转测试操作员过载



我的旋转测试功能与学校的不匹配。请告诉我哪里出了问题。这么长时间以来,我一直试图解决这个问题,但没有成功。谢谢

**********我的旋转测试**********

旋转45.000度的点(-50.000,-50.000)为(0.000,0.000)

旋转45.000度的点(-6.000,-6.000)为(0.000,0.000)

**********学校轮考**********

旋转45.000度的点(-50.000,-50.000)为(0.000,-70.711)

旋转45.000度的点(-6.000,-6.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);
}

最新更新