编译器:C++ (g++) 在一个平面内,由左上角(top left)顶点坐标结合右下角(bottom right)顶点坐标即可确定一个平面矩形。请设计Rect和Point类,使其可以被下述代码所利用,并产生期望的输出。 裁判测试程序样例: //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; } 输入样例: 输出样例: 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()计算并返回矩形的对角线长度,使用勾股定理进行计算。
时间: 2023-10-21 13:03:31 浏览: 144
代码如下:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
int x, y;
Point(int x_, int y_) {
x = x_;
y = y_;
}
};
class Rect {
public:
Point tl, br;
Rect(Point tl_, Point br_) {
tl = tl_;
br = br_;
}
Point topRight() {
Point tr(br.x, tl.y);
return tr;
}
Point bottomLeft() {
Point bl(tl.x, br.y);
return bl;
}
int width() {
return abs(br.x - tl.x);
}
int height() {
return abs(tl.y - br.y);
}
int area() {
return width() * height();
}
double diagonalLength() {
return sqrt(width() * width() + height() * height());
}
};
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;
}
```
阅读全文