C++ 等分三点圆n点 源代码
时间: 2024-03-22 17:38:24 浏览: 87
OpenCV实现的椭圆检测的源代码
3星 · 编辑精心推荐
以下是一个简单的 C++ 源代码,用于计算等分 $n$ 点圆的坐标:
```cpp
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
const double EPS = 1e-6; // 浮点误差
int n; // 点的个数
vector<pair<double, double>> points; // 存储点的坐标
// 计算两个点之间的距离
double dist(double x1, double y1, double x2, double y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
// 计算圆心坐标
pair<double, double> getCenter(double x1, double y1, double x2, double y2, double x3, double y3) {
double a = x2 - x1;
double b = y2 - y1;
double c = x3 - x1;
double d = y3 - y1;
double e = a * (x1 + x2) + b * (y1 + y2);
double f = c * (x1 + x3) + d * (y1 + y3);
double g = 2.0 * (a * (y3 - y2) - b * (x3 - x2));
if (fabs(g) < EPS) {
// 三点共线
return make_pair(-1, -1);
}
double centerX = (d * e - b * f) / g;
double centerY = (a * f - c * e) / g;
return make_pair(centerX, centerY);
}
// 判断是否所有点都在圆内
bool isAllInCircle(double centerX, double centerY, double radius) {
for (int i = 0; i < n; i++) {
double d = dist(centerX, centerY, points[i].first, points[i].second);
if (d > radius + EPS) {
return false;
}
}
return true;
}
// 计算等分n点圆的圆心坐标和半径
pair<double, double> getCenterAndRadius() {
pair<double, double> center = make_pair(-1, -1); // 圆心坐标初始化为 (-1, -1)
double radius = -1; // 半径初始化为 -1
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
pair<double, double> c = getCenter(points[i].first, points[i].second, points[j].first, points[j].second, points[k].first, points[k].second);
if (c.first == -1 && c.second == -1) {
// 三点共线,无法构成等分三点圆
continue;
}
double r = dist(c.first, c.second, points[i].first, points[i].second);
if (r < radius || radius < 0) {
// 如果计算出来的圆半径比之前的小,则更新圆心坐标和半径
if (isAllInCircle(c.first, c.second, r)) {
center = c;
radius = r;
}
}
}
}
}
return make_pair(center.first, radius);
}
int main() {
cout << "请输入点的个数:" << endl;
cin >> n;
cout << "请输入每个点的坐标:" << endl;
for (int i = 0; i < n; i++) {
double x, y;
cin >> x >> y;
points.push_back(make_pair(x, y));
}
pair<double, double> center = getCenterAndRadius();
if (center.first == -1 && center.second == -1) {
cout << "无法构成等分 " << n << " 点圆!" << endl;
} else {
cout << "等分 " << n << " 点圆的圆心坐标为(" << center.first << ", " << center.second << ")" << endl;
cout << "等分 " << n << " 点圆的半径为" << center.second << endl;
}
return 0;
}
```
这段代码使用输入的 $n$ 个点的坐标计算等分 $n$ 点圆的圆心坐标和半径,并输出结果。
阅读全文