求两条异面直线的距离、与公垂线的交点坐标
先
①作直线a、b的方向向量a、b,求a、b的法向量n,即此异面直线a、b的公垂线的方向向量;②在直线a、b上各取一点A、B,作向量AB;③求向量AB在向量n上的射影d,则异面直线a、b间的距离为
再
http://blog.sina.com.cn/s/blog_648868460100h1sf.html 套入公式
#include <stdio.h>
#include <math.h>
double dis(double x, double y, double z)
{
return sqrt(fabs(x*x+y*y+z*z));
}
int main()
{
double x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
double nx, ny, nz, ax, ay, az, bx, by, bz, d;
double x, y, z, X, Y, Z, k, K, H, I, J, L, M, N, O, P, Q;
int t;
scanf("%d", &t);
while(t--)
{
scanf("%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &x1, &y1, &z1, &x2, &y2, &z2, &x3, &y3, &z3, &x4, &y4, &z4);
ax = x1 - x2, ay = y1 - y2, az = z1 - z2;
bx = x3 - x4, by = y3 - y4, bz = z3 - z4;
nx = ay*bz - az*by;
ny = -ax*bz + az*bx;
nz = ax*by - ay*bx;
//printf("%.6lf %.6lf %.6lf\n", (x2-x1)*nx + (y2-y1)*ny + (z2-z1)*nz, ny, nz);
d = fabs((x3-x1)*nx + (y3-y1)*ny + (z3-z1)*nz) / dis(nx, ny, nz);
//printf("%.6lf %.6lf %.6lf\n", );
H = x2 - x1, I = y2 - y1, J = z2 - z1;
K = x4 - x3, L = y4 - y3, M = z4 - z3;
N = H*I*L-I*I*K-J*J*K+H*J*M;
O = H*H*L-H*I*K-I*J*M+J*J*L;
P = H*J*K-H*H*M-I*I*M+I*J*L;
Q = -x1*N+y1*O-z1*P;
k = (O*y3-N*x3-P*z3-Q) / (N*K-O*L+P*M);
x = K*k+x3;
y = L*k+y3;
z = M*k+z3;
H = x4 - x3, I = y4 - y3, J = z4 - z3;
K = x2 - x1, L = y2 - y1, M = z2 - z1;
N = H*I*L-I*I*K-J*J*K+H*J*M;
O = H*H*L-H*I*K-I*J*M+J*J*L;
P = H*J*K-H*H*M-I*I*M+I*J*L;
Q = -x3*N+y3*O-z3*P;
k = (O*y1-N*x1-P*z1-Q) / (N*K-O*L+P*M);
X = K*k+x1;
Y = L*k+y1;
Z = M*k+z1;
printf("%.6lf\n", d);
printf("%.6lf %.6lf %.6lf %.6lf %.6lf %.6lf\n", X, Y, Z, x, y, z);
}
}