我试图弄清楚为什么不管输入的int值是哪种类型,该程序始终输出Rectangles Do Not Overlap
。
我已经尝试在if
函数中修复我的isRectangleOverlap()
语句,但由于某些原因,输出仍然保持不变。
一个矩形表示为列表[x1,y1,x2,y2],其中(x1,y1)是其左下角的坐标,而(x2,y2)是其右上角的坐标。
它不输出以下示例:
示例1:输入:rec1 = [0,0,2,2],rec2 = [1,1,3,3]输出:矩形重叠
示例2:输入:rec1 = [0,0,1,1],rec2 = [1,0,2,1]输出:矩形不重叠
要清楚,两个仅在角或边缘接触的矩形不重叠。
#include <iostream>
#include <vector>
using namespace std;
struct Point{
int x, y;
};
bool isRectangleOverlap(Point t1, Point b1, Point t2, Point b2){
if ((t1.x <= t2.x && b2.x <= b1.x) && (t1.y >= t2.y && b2.y >= b1.y)) {
return true;
}
else if ((t2.x <= t1.x && b1.x <= b2.x) && (t2.y >= t1.y && b1.y >= b2.y)) {
return true;
}
else {
return false;
}
}
int main() {
Point top1, top2, bottom1, bottom2;
cout << "First Top Point: ";
cin >> top1.x;
cin >> top1.y;
cout << endl;
cout << "First Bottom Point: ";
cin >> bottom1.x;
cin >> bottom1.y;
cout << endl;
cout << "Second Top Point: ";
cin >> top2.x;
cin >> top2.y;
cout << endl;
cout << "Second Bottom Point: ";
cin >> bottom2.x;
cin >> bottom2.y;
cout << endl;
if (isRectangleOverlap(top1, bottom1, top2, bottom2)){
cout << "Rectangles Overlap" << endl;
}
else
{
cout << "Rectangles Do Not Overlap" << endl;
};
return 0;
}
我希望输出结果如上面的示例中所述。
这里是一种方法。检查矩形可能不重叠的所有条件。为此,以一个矩形作为参考,然后检查另一个矩形是否位于参考矩形的左侧,右侧,顶部或底部。如果没有,它必须重叠。这是代码。
#include <iostream>
#include <vector>
using namespace std;
struct Rectangle {
int x1;
int y1;
int x2;
int y2;
};
bool isOverlap(Rectangle a, Rectangle b)
{
bool overlap;
if (b.y1 >= a.y2)
overlap = false;
else if (b.x1 >= a.x2)
overlap = false;
else if (a.y1 >= b.y2)
overlap = false;
else if (a.x1 >= b.x2)
overlap = false;
else
overlap = true;
return overlap;
}
void printPoints(Rectangle &rect)
{
cout << "Rectangle bottom-left: (" << rect.x1 << ", " << rect.y1 << ")" << endl;
cout << "Rectangle top-right: (" << rect.x2 << ", " << rect.y2 << ")" << endl;
}
void getInput(Rectangle &rect)
{
cout << "Enter rectangle. x1: "<< endl;
cin >> rect.x1;
cout << "Enter rectangle. y1: "<< endl;
cin >> rect.y1;
cout << "Enter rectangle. x2: "<< endl;
cin >> rect.x2;
cout << "Enter rectangle. y2: "<< endl;
cin >> rect.y2;
}
void testRectangleOverlap()
{
Rectangle a;
Rectangle b;
getInput(a);
getInput(b);
printPoints(a);
printPoints(b);
if (isOverlap(a, b)){
cout << "Rectangles Overlap" << endl;
}
else
{
cout << "Rectangles Do Not Overlap" << endl;
}
}
int main() {
testRectangleOverlap();
return 0;
}
在这里您可以使用代码:live code