C++ 判断两矩形是否有公共部分 给出左下角、右上角坐标 用代码写出
下面是一个用C++编写的判断两个矩形是否有公共部分的代码:
#include <iostream>
struct Point {
int x;
int y;
};
bool isOverlap(Point bottomLeft1, Point topRight1, Point bottomLeft2, Point topRight2) {
// 判断两个矩形是否有公共部分
if (bottomLeft1.x > topRight2.x || bottomLeft2.x > topRight1.x) {
return false;
}
if (topRight1.y > bottomLeft2.y || topRight2.y > bottomLeft1.y) {
return false;
}
return true;
}
int main() {
// 测试用例
Point bottomLeft1 = {1, 1};
Point topRight1 = {3, 3};
Point bottomLeft2 = {2, 2};
Point topRight2 = {4, 4};
if (isOverlap(bottomLeft1, topRight1, bottomLeft2, topRight2)) {
std::cout << "两个矩形有公共部分" << std::endl;
} else {
std::cout << "两个矩形没有公共部分" << std::endl;
}
return 0;
}
该代码首先定义了一个Point结构体,用于表示一个点的坐标。然后定义了一个isOverlap函数,用于判断两个矩形是否有公共部分。isOverlap函数接受四个参数,分别是两个矩形的左下角和右上角坐标。函数内部通过比较两个矩形的坐标来判断它们是否有公共部分。
在main函数中,我们定义了两个测试用例,然后调用isOverlap函数判断两个矩形是否有公共部分,并输出结果
原文地址: https://www.cveoy.top/t/topic/iERq 著作权归作者所有。请勿转载和采集!