三个矩形重叠面积C语言代码
时间: 2024-10-21 14:08:36 浏览: 9
在C语言中,计算三个矩形重叠部分的面积需要先确定这三个矩形是否真的有重叠。这里假设每个矩形由两个点(x1, y1)和(x2, y2)定义其左上角和右下角。下面是一个简单的示例代码:
```c
#include <stdio.h>
// 定义矩形结构体
typedef struct {
int x1, y1; // 左上角坐标
int x2, y2; // 右下角坐标
} Rectangle;
// 计算并返回两个矩形的交集面积
int overlap_area(Rectangle rect1, Rectangle rect2) {
int min_x = (rect1.x1 > rect2.x1) ? rect2.x1 : rect1.x1;
int max_x = (rect1.x2 < rect2.x2) ? rect1.x2 : rect2.x2;
int min_y = (rect1.y1 > rect2.y1) ? rect2.y1 : rect1.y1;
int max_y = (rect1.y2 < rect2.y2) ? rect1.y2 : rect2.y2;
if (min_x >= max_x || min_y >= max_y)
return 0; // 没有重叠
return (max_x - min_x) * (max_y - min_y);
}
// 主函数:计算三个矩形的重叠面积
int main() {
Rectangle rect1 = {1, 1, 4, 6};
Rectangle rect2 = {3, 2, 5, 7};
Rectangle rect3 = {2, 3, 6, 5};
int total_overlap = overlap_area(rect1, rect2);
total_overlap += overlap_area(rect1, rect3);
total_overlap += overlap_area(rect2, rect3);
printf("三个矩形的重叠面积为: %d\n", total_overlap);
return 0;
}
```
阅读全文