用c++创建一个矩形类,矩形的边平行于坐标轴。矩形的属性用其左下角坐标、长度和宽度描述。 (1) 从键盘输入两个矩形参数(注意输入提示信息),创建两个矩形对象, 判断两个矩形是否相交?求出相交部分的面积。 (2) 从键盘再输入或随机产生3个矩形对象,对输入的所有5个矩形按面积由小到大排序, 然后依次显示各个矩形的左下角坐标、长、宽、面积。
时间: 2024-03-02 09:51:23 浏览: 87
好的,我可以帮你解决这个问题。以下是 C++ 实现:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
class Rectangle {
private:
double x, y;
double width, height;
public:
Rectangle(double x, double y, double w, double h) {
this->x = x;
this->y = y;
this->width = w;
this->height = h;
}
double getX() { return x; }
double getY() { return y; }
double getWidth() { return width; }
double getHeight() { return height; }
double getArea() { return width * height; }
bool intersect(Rectangle rect) {
double x1 = max(x, rect.getX());
double y1 = max(y, rect.getY());
double x2 = min(x + width, rect.getX() + rect.getWidth());
double y2 = min(y + height, rect.getY() + rect.getHeight());
return (x1 < x2) && (y1 < y2);
}
Rectangle getIntersection(Rectangle rect) {
double x1 = max(x, rect.getX());
double y1 = max(y, rect.getY());
double x2 = min(x + width, rect.getX() + rect.getWidth());
double y2 = min(y + height, rect.getY() + rect.getHeight());
double intWidth = x2 - x1;
double intHeight = y2 - y1;
return Rectangle(x1, y1, intWidth, intHeight);
}
};
bool compare(Rectangle rect1, Rectangle rect2) {
return rect1.getArea() < rect2.getArea();
}
int main() {
double x1, y1, w1, h1;
double x2, y2, w2, h2;
cout << "请输入第一个矩形的左下角坐标、长和宽(用空格隔开):";
cin >> x1 >> y1 >> w1 >> h1;
Rectangle rect1(x1, y1, w1, h1);
cout << "请输入第二个矩形的左下角坐标、长和宽(用空格隔开):";
cin >> x2 >> y2 >> w2 >> h2;
Rectangle rect2(x2, y2, w2, h2);
if (rect1.intersect(rect2)) {
Rectangle intersection = rect1.getIntersection(rect2);
cout << "两个矩形相交,相交部分的面积为:" << intersection.getArea() << endl;
} else {
cout << "两个矩形不相交" << endl;
}
Rectangle rects[5] = {rect1, rect2};
for (int i = 2; i < 5; i++) {
double x, y, w, h;
cout << "请输入第" << i << "个矩形的左下角坐标、长和宽(用空格隔开):";
cin >> x >> y >> w >> h;
Rectangle rect(x, y, w, h);
rects[i] = rect;
}
sort(rects, rects + 5, compare);
for (int i = 0; i < 5; i++) {
Rectangle rect = rects[i];
cout << "矩形" << i + 1 << ":左下角坐标(" << rect.getX() << ", " << rect.getY()
<< "),长:" << rect.getWidth() << ",宽:" << rect.getHeight()
<< ",面积:" << rect.getArea() << endl;
}
return 0;
}
```
运行程序后,输入两个矩形的参数,程序会判断两个矩形是否相交,并计算相交部分的面积。然后再输入或随机生成3个矩形,对5个矩形按面积从小到大排序,并依次显示各个矩形的参数和面积。
阅读全文