已知圆上三点求圆心和半径,用c++
时间: 2023-09-19 19:11:43 浏览: 59
以下是用 C++ 实现已知圆上三点求圆心和半径的代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
double x, y;
};
// 计算两点之间的距离
double distance(Point p1, Point p2) {
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
}
// 已知圆上三点求圆心和半径
void circleFromPoints(Point p1, Point p2, Point p3, Point& center, double& radius) {
double a = distance(p1, p2);
double b = distance(p2, p3);
double c = distance(p3, p1);
double s = (a + b + c) / 2;
double area = sqrt(s * (s - a) * (s - b) * (s - c));
double A = asin((p2.y - p1.y) / a);
double B = asin((p3.y - p1.y) / c);
double x = area * (cos(A) + cos(B)) / (sin(A) + sin(B)) / 2 + p1.x;
double y = (p2.y - p1.y) / (p2.x - p1.x) * (x - (p1.x + p2.x) / 2) + (p1.y + p2.y) / 2;
center.x = x;
center.y = y;
radius = distance(center, p1);
}
int main() {
Point p1 = { 0, 0 };
Point p2 = { 1, 1 };
Point p3 = { 2, 0 };
Point center;
double radius;
circleFromPoints(p1, p2, p3, center, radius);
cout << "Center: (" << center.x << ", " << center.y << ")" << endl;
cout << "Radius: " << radius << endl;
return 0;
}
```
在本例中,我们定义了一个 `Point` 结构体来表示点的坐标,并定义了一个 `distance` 函数来计算两点之间的距离。`circleFromPoints` 函数接收三个点作为参数,并计算出圆心和半径,结果保存在 `center` 和 `radius` 变量中。主函数中调用 `circleFromPoints` 函数,并输出圆心和半径的值。