用c++ 写一下判断钜形和圆重叠
时间: 2024-02-16 13:05:17 浏览: 74
圆和矩形是否重叠leetcode-leetcode_solutions:leetcode_solutions
好的,以下是C++代码实现判断矩形和圆形是否重叠:
```c++
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
double x, y;
};
bool isOverlap(Point center, double radius, Point rectCorner1, Point rectCorner2) {
// 计算矩形中心点
Point rectCenter;
rectCenter.x = (rectCorner1.x + rectCorner2.x) / 2;
rectCenter.y = (rectCorner1.y + rectCorner2.y) / 2;
// 计算矩形宽度和高度
double rectWidth = abs(rectCorner1.x - rectCorner2.x);
double rectHeight = abs(rectCorner1.y - rectCorner2.y);
// 计算圆心到矩形中心的距离
double distance = sqrt(pow(center.x - rectCenter.x, 2) + pow(center.y - rectCenter.y, 2));
// 判断是否重叠
if (distance <= radius + sqrt(pow(rectWidth, 2) + pow(rectHeight, 2)) / 2) {
return true;
}
else {
return false;
}
}
int main() {
Point center = { 0, 0 };
double radius = 2;
Point rectCorner1 = { -1, -1 };
Point rectCorner2 = { 1, 1 };
if (isOverlap(center, radius, rectCorner1, rectCorner2)) {
cout << "Circle and rectangle are overlapping." << endl;
}
else {
cout << "Circle and rectangle are not overlapping." << endl;
}
return 0;
}
```
这里的 `isOverlap` 函数接收圆心和半径,以及矩形的两个对角点作为参数,返回是否重叠的布尔值。
阅读全文