6-94.平面矩形

编译器:C++ (g++)

在一个平面内,由左上角(top left)顶点坐标结合右下角(bottom right)顶点坐标即可确定一个平面矩形。请设计Rect和Point类,使其可以被下述代码所利用,并产生期望的输出。

裁判测试程序样例:

输入样例:

输出样例:

Vertices of rectangle rt:

(1,6)-----------------------(7,6)

(1,8)-----------------------(7,8)

Size information of rectangle rt:

width - 6    height - 2

area - 12    diagonal legnth - 6.32

请注意:函数题只需要提交相关代码片段,不要提交完整程序。

  • Point topRight()生成并返回矩形右上角顶点坐标;

  • Point bottomLeft()生成并返回矩形左下角顶点的坐标;

  • 属性Point tl表示左上角顶点坐标, br表示右下角顶点坐标;

  • int width(), int height()分别计算并返回矩形的宽,高;

  • double diagonalLength()计算并返回矩形的对角线长度,使用勾股定理进行计算。

//Project  -  Rect
#include  <iostream>
#include  <cmath>
using  namespace  std;

//定义Point类
//定义Rect类
int  main()  {
        auto  rt  =  Rect(Point(1,6),Point(7,8));
        printf("Vertices  of  rectangle  rt:\n");
        printf("(%d,%d)-----------------------(%d,%d)\n",
                      rt.tl.x,rt.tl.y,rt.topRight().x,rt.topRight().y);

        printf("(%d,%d)-----------------------(%d,%d)\n",
                      rt.bottomLeft().x,rt.bottomLeft().y,rt.br.x,rt.br.y);

        printf("Size  information  of  rectangle  rt:\n");
        printf("width  -  %d        height  -  %d\n",rt.width(),rt.height());
        printf("area  -  %d        diagonal  legnth  -  %.2f",rt.area(),rt.diagonalLength());

        return  0;
}

Ans:

//定义Point类
class Point {
public:
    int x;
    int y;
    Point(int x, int y):x(x),y(y){}
    Point(){}
};
//定义Rect类
class Rect {
public:
    Point tl;
    Point br;
    Rect(const Point& a, const Point& b) {
        this->tl = a;
        this->br = b;
    }

    Point topRight() {
        Point temp(br.x, tl.y);
        return temp;
    }

    Point bottomLeft() {
        Point temp(tl.x, br.y);
        return temp;
    }

    int width() {
        return abs(br.x - tl.x);
    }

    int height() {
        return abs(tl.y - br.y);
    }

    int area() {
        return abs(br.x - tl.x) * abs(tl.y - br.y);
    }

    double diagonalLength() {
        return sqrt(pow(abs(br.x - tl.x), 2) + pow(abs(tl.y - br.y), 2));
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值