写一段C++代码,实现两个坐标为整数的矩形求交
时间: 2024-05-14 10:19:47 浏览: 91
好的,以下是代码:
```c
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point tl; // top-left point
Point br; // bottom-right point
} Rect;
// 判断两个矩形是否有交集
int has_intersect(Rect rect1, Rect rect2) {
if (rect1.tl.x > rect2.br.x || rect2.tl.x > rect1.br.x) {
return 0;
}
if (rect1.tl.y < rect2.br.y || rect2.tl.y < rect1.br.y) {
return 0;
}
return 1;
}
// 计算两个矩形的交集
Rect get_intersect(Rect rect1, Rect rect2) {
Rect rect = {0};
if (!has_intersect(rect1, rect2)) {
return rect;
}
rect.tl.x = rect1.tl.x > rect2.tl.x ? rect1.tl.x : rect2.tl.x;
rect.tl.y = rect1.tl.y < rect2.tl.y ? rect1.tl.y : rect2.tl.y;
rect.br.x = rect1.br.x < rect2.br.x ? rect1.br.x : rect2.br.x;
rect.br.y = rect1.br.y > rect2.br.y ? rect1.br.y : rect2.br.y;
return rect;
}
// 测试代码
int main() {
Rect rect1 = {{0, 0}, {4, 4}};
Rect rect2 = {{2, 2}, {6, 6}};
Rect rect3 = {{5, 5}, {7, 7}};
Rect rect_intersect;
rect_intersect = get_intersect(rect1, rect2);
printf("(%d,%d)-(%d,%d)\n", rect_intersect.tl.x, rect_intersect.tl.y, rect_intersect.br.x, rect_intersect.br.y);
rect_intersect = get_intersect(rect1, rect3);
printf("(%d,%d)-(%d,%d)\n", rect_intersect.tl.x, rect_intersect.tl.y, rect_intersect.br.x, rect_intersect.br.y);
return 0;
}
```
这段代码实现了两个坐标为整数的矩形求交的功能,具体的实现过程就是判断两个矩形是否有交集,如果有,再计算出它们的交集矩形。值得注意的是,我们这里使用了 C 语言中的一些结构体和指针的技巧,来使代码的结构更加清晰和简洁。
阅读全文