用c++实现点到面的距离
时间: 2023-05-30 11:03:57 浏览: 76
不确定你是想求点到一个平面的距离,还是点到一个多边形的距离,以下是两种情况的代码实现:
1. 点到平面的距离:
```c
#include <stdio.h>
#include <math.h>
typedef struct {
float x, y, z;
} Point3D;
typedef struct {
float a, b, c, d;
} Plane;
float distanceToPlane(Point3D p, Plane plane) {
float numerator = fabs(plane.a * p.x + plane.b * p.y + plane.c * p.z + plane.d);
float denominator = sqrt(plane.a * plane.a + plane.b * plane.b + plane.c * plane.c);
return numerator / denominator;
}
int main() {
Point3D p = {1, 2, 3};
Plane plane = {1, 2, 3, 4};
printf("Distance from point (%.2f, %.2f, %.2f) to plane (%.2fx + %.2fy + %.2fz + %.2f) is %.2f.\n", p.x, p.y, p.z, plane.a, plane.b, plane.c, plane.d, distanceToPlane(p, plane));
return 0;
}
```
2. 点到多边形的距离:
```c
#include <stdio.h>
#include <math.h>
typedef struct {
float x, y, z;
} Point3D;
typedef struct {
int n; // number of vertices
Point3D* vertices; // vertex array
} Polygon;
float distanceToPolygon(Point3D p, Polygon poly) {
float minDistance = INFINITY;
for (int i = 0; i < poly.n; i++) {
Point3D v1 = poly.vertices[i];
Point3D v2 = poly.vertices[(i + 1) % poly.n];
float distance = fabs((v2.y - v1.y) * p.x - (v2.x - v1.x) * p.y + v2.x * v1.y - v2.y * v1.x) / sqrt((v2.y - v1.y) * (v2.y - v1.y) + (v2.x - v1.x) * (v2.x - v1.x));
if (distance < minDistance) {
minDistance = distance;
}
}
return minDistance;
}
int main() {
Point3D p = {1, 2, 3};
Point3D vertices[] = {{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}};
Polygon poly = {4, vertices};
printf("Distance from point (%.2f, %.2f, %.2f) to polygon with vertices:\n", p.x, p.y, p.z);
for (int i = 0; i < poly.n; i++) {
printf("(%.2f, %.2f, %.2f) ", poly.vertices[i].x, poly.vertices[i].y, poly.vertices[i].z);
}
printf("\nis %.2f.\n", distanceToPolygon(p, poly));
return 0;
}
```