编译器: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));
}
};