计算三维点到空间线距离的C++代码
时间: 2023-05-18 11:07:16 浏览: 161
以下是计算三维点到空间线距离的C代码:
#include <stdio.h>
#include <math.h>
typedef struct {
double x, y, z;
} Point3D;
typedef struct {
Point3D p1, p2;
} Line3D;
double distancePointLine(Point3D p, Line3D l) {
double dx = l.p2.x - l.p1.x;
double dy = l.p2.y - l.p1.y;
double dz = l.p2.z - l.p1.z;
double t = ((p.x - l.p1.x) * dx + (p.y - l.p1.y) * dy + (p.z - l.p1.z) * dz) / (dx * dx + dy * dy + dz * dz);
Point3D projection = {l.p1.x + t * dx, l.p1.y + t * dy, l.p1.z + t * dz};
return sqrt(pow(projection.x - p.x, 2) + pow(projection.y - p.y, 2) + pow(projection.z - p.z, 2));
}
int main() {
Point3D p = {1, 2, 3};
Line3D l = {{0, 0, 0}, {1, 1, 1}};
printf("Distance from point (%.2f, %.2f, %.2f) to line ((%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f)) is %.2f\n", p.x, p.y, p.z, l.p1.x, l.p1.y, l.p1.z, l.p2.x, l.p2.y, l.p2.z, distancePointLine(p, l));
return 0;
}
阅读全文