C++程序怎么写

2025-03-18 18:42:01
推荐回答(1个)
回答1:

按照以上要求用C++实现CPoint类和CRectangle类,并进行相应的运算,关于多文件结构,你自行整一下,这里不好发,参考代码如下:

#include
#include
using namespace std;
class CPoint {
    double x,y;
public :
CPoint(double x, double y):x(x),y(y) {}
    CPoint(const CPoint &p):x(p.x),y(p.y) {}
    double GetX() const {
        return x;
    }
    double GetY() const {
        return y;
    }
    void SetX(double x) {
        this->x=x;
    }
    void SetY(double y) {
        this->y=y;
    }
};
class CRectangle {
    CPoint cl,cr;
public :
    CRectangle(const CPoint cl, const CPoint cr):cl(cl),cr(cr) {}
    CRectangle(double x1, double y1, double x2, double y2):cl(x1,y1),cr(x2,y2) {}
    void SetLPoint(const CPoint cl) {
        this->cl.SetX(cl.GetX());
        this->cl.SetY(cl.GetY());
    }
    void SetRPoint(const CPoint cr) {
        this->cr.SetX(cr.GetX());
        this->cr.SetY(cr.GetY());
    }
    double GetPerimeter() {
        return 2*(fabs(cr.GetX()-cl.GetX())+fabs(cr.GetY()-cl.GetY()));
    }
    double GetArea() {
        return (fabs(cr.GetX()-cl.GetX())*fabs(cr.GetY()-cl.GetY()));
    }
};
int main()
{
    int SIZE,i;
    double x1,y1,x2,y2;
    double sum=0,max,t;
    CPoint cl(2,5),cr(6,8);
    CRectangle a_rectagnle(cl,cr);
    CRectangle **rectagnles;
    cout << "a的周长" <    cout << "a的面积" <    a_rectagnle.SetLPoint(*(new CPoint(4,6)));
    a_rectagnle.SetRPoint(*(new CPoint(7,9)));
    cout << "a的周长" <    cout << "a的面积" <    cout << "输入SIZE:";
    cin >> SIZE;
    cout <<"输入"<    rectagnles = new CRectangle*[SIZE];
    for(i=0; i        cout <<"x1 y1 x2 y2:"<< endl;
        cin >> x1>>y1;
        cin >> x2>>y2;
        rectagnles[i]=new CRectangle(x1,y1,x2,y2);
    }
    sum=max=rectagnles[0]->GetArea();
    for(i=1; i        t=rectagnles[i]->GetArea();
        sum+=t;
        max=max>t?max:t;
    }
    cout << "平均面积为" <    cout << "最大面积为" <    for(i=0; i        delete rectagnles[i];
    delete []rectagnles;
    return 0;
}