找出平面上的4个点是否形成一个矩形? [英] find if 4 points on a plane form a rectangle?
问题描述
有人可以用 C 风格的伪代码告诉我如何编写一个函数(表示你喜欢的点),如果 4 点(函数的参数)形成一个矩形,则返回 true,否则返回 false?
我想出了一个解决方案,首先尝试找到 2 对具有相同 x 值的不同点,然后对 y 轴执行此操作.但是代码比较长.只是想看看其他人的想法.
- 求角点的质心:cx=(x1+x2+x3+x4)/4, cy=(y1+y2+y3+y4)/4
- 测试从质心到所有 4 个角的距离的平方是否相等
bool isRectangle(double x1, double y1,双 x2,双 y2,双 x3,双 y3,双 x4,双 y4){双 cx,cy;双 dd1,dd2,dd3,dd4;cx=(x1+x2+x3+x4)/4;cy=(y1+y2+y3+y4)/4;dd1=sqr(cx-x1)+sqr(cy-y1);dd2=sqr(cx-x2)+sqr(cy-y2);dd3=sqr(cx-x3)+sqr(cy-y3);dd4=sqr(cx-x4)+sqr(cy-y4);返回 dd1==dd2 &&dd1==dd3 &&dd1==dd4;}
(当然在实践中测试两个浮点数 a 和 b 的相等性应该以有限的精度进行:例如 abs(a-b) < 1E-6)
Can somebody please show me in C-style pseudocode how to write a function (represent the points however you like) that returns true if 4-points (args to the function) form a rectangle, and false otherwise?
I came up with a solution that first tries to find 2 distinct pairs of points with equal x-value, then does this for the y-axis. But the code is rather long. Just curious to see what others come up with.
- find the center of mass of corner points: cx=(x1+x2+x3+x4)/4, cy=(y1+y2+y3+y4)/4
- test if square of distances from center of mass to all 4 corners are equal
bool isRectangle(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { double cx,cy; double dd1,dd2,dd3,dd4; cx=(x1+x2+x3+x4)/4; cy=(y1+y2+y3+y4)/4; dd1=sqr(cx-x1)+sqr(cy-y1); dd2=sqr(cx-x2)+sqr(cy-y2); dd3=sqr(cx-x3)+sqr(cy-y3); dd4=sqr(cx-x4)+sqr(cy-y4); return dd1==dd2 && dd1==dd3 && dd1==dd4; }
(Of course in practice testing for equality of two floating point numbers a and b should be done with finite accuracy: e.g. abs(a-b) < 1E-6)
这篇关于找出平面上的4个点是否形成一个矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!