这道题会暴露很多孩纸的高数学的好不好。如何计算三维直线的最短距离和垂足的坐标,学习链接
之后的就是代入公式计算了。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <stdio.h> 2 #include <math.h> 3 struct Point { 4 double x, y, z; 5 Point(double x = 0, double y = 0, double z = 0):x(x), y(y), z(z) {} 6 void read() { 7 scanf("%lf%lf%lf", &x, &y, &z); 8 } 9 void write() { 10 printf("%.6lf%.6lf%.6lf", x, y, z); 11 } 12 Point operator + (const Point &b) { 13 return Point(x + b.x, y + b.y, z + b.z); 14 } 15 Point operator - (const Point &b) { 16 return Point(x - b.x, y - b.y, z - b.z); 17 } 18 Point operator * (double k) { 19 return Point(x * k, y * k, z * k); 20 } 21 Point operator / (double k) { 22 return Point(x / k, y / k, z / k); 23 } 24 Point cross(const Point &b) { 25 return Point(y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x); 26 } 27 double len() { 28 return sqrt(x * x + y * y + z * z); 29 } 30 double operator * (const Point &b) { 31 return x * b.x + y * b.y + z * b.z; 32 } 33 }; 34 typedef Point Vector; 35 int main() { 36 int T; 37 scanf("%d", &T); 38 while (T--) { 39 Point A, B, C, D; 40 A.read(); 41 B.read(); 42 C.read(); 43 D.read(); 44 Vector AB= B - A, CD = D - C; 45 Vector n = AB.cross(CD), AC = C - A, CA = A - C; 46 double nlen = n.len(), dis = n * AC / nlen; 47 double t1 = AC.cross(CD) * AB.cross(CD) / nlen / nlen; 48 double t2 = CA.cross(AB) * CD.cross(AB) / nlen / nlen; 49 Point E = A + (AB * t1); 50 Point F = C + (CD * t2); 51 if (dis < 0) 52 dis = -dis; 53 printf("%.6lf\n", dis); 54 E.write(); 55 putchar(' '); 56 F.write(); 57 putchar('\n'); 58 } 59 return 0; 60 }