有人可以请告诉我在C风格的伪code如何写一个函数(重present点你喜欢的),返回true,如果4点(参数给函数)形成一个矩形,否则为假?
我想出了一个解决方案,首先试图找到2个不同的点对具有同等的x值,则这是否为y轴。但是,code是相当长的。只是好奇,看看别人拿出。
解决方案 找到的角点的质量中心:CX =(X1 + X2 + X3 + X4)/ 4,CY =(Y1 + Y2 + Y3 + Y4)/ 4 测试,如果距离从质量中心的所有4个角的方形相等 布尔isRectangle(双X1,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(AB)< 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)