判断方法分为两步:
1.判断四条边是否相等;
2.判断是否有一个角为直角;
求解两点之前距离的函数:
?| 1 2 3 |
double Distance(int x1,int y1,int x2,int y2){
return sqrt(pow((x1-x2),2)+pow((y1-y2),2));
}
|
判断三点连续构成的角是否为直角,第一个点参数为顶点:
?| 1 2 3 4 5 |
bool IsRightAngle(int x1,int y1,int x2,int y2,int x3,int y3){
if((x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)==0)
return true;
return false;
}
|
完整的程序:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <iostream>
#include <math.h>
using namespace std;
//直接调用IsSquare函数,输入为四个点的坐标,输出为true or false;
//求两点间的距离
double Distance(int x1,int y1,int x2,int y2){
return sqrt(pow((x1-x2),2)+pow((y1-y2),2));
}
//判断三个点是否构成直角,第一个参数点是顶点
bool IsRightAngle(int x1,int y1,int x2,int y2,int x3,int y3){
if((x2-x1)*(x3-x1)+(y2-y1)*(y3-y1)==0)
return true;
return false;
}
bool IsSquare(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){
if(x1==x2&&x2==x3)
return false;
double s12=Distance(x1,y1,x2,y2);
double s13=Distance(x1,y1,x3,y3);
double s14=Distance(x1,y1,x4,y4);
double s23=Distance(x2,y2,x3,y3);
double s24=Distance(x2,y2,x4,y4);
double s34=Distance(x3,y3,x4,y4);
if(s12==s13&&s24==s34&&s12==s24){
if(IsRightAngle(x1,y1,x2,y2,x3,y3)) return true;
else return false;
}
if(s12==s14&&s23==s34&&s12==s23){
if(IsRightAngle(x1,y1,x2,y2,x4,y4)) return true;
else return false;
}
if(s13==s14&&s23==s24&&s13==s23){
if(IsRightAngle(x1,y1,x3,y3,x4,y4)) return true;
else return false;
}
return false;
}
int main(){
int x1,y1,x2,y2,x3,y3,x4,y4;
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
cout<<IsSquare(x1,y1,x2,y2,x3,y3,x4,y4)<<endl;
return 0;
}
|
测试用例:
?| 1 |
0 1 1 0 1 1 0 0
|
输出结果为1(true)
补充:判断四个点是否可以构成矩形(优雅的解法!!!)
首先我们需要先检查输入的四个点是不是有重复。然后判断四个角是不是直角即可。
?| 1 2 3 4 5 6 |
def isOrthogonal(p1, p2, p3):
return (p2[0] - p1[0]) * (p2[0] - p3[0]) + (p2[1] - p1[1]) * (p2[1] - p3[1]) == 0
def _isRectangle(p1, p2, p3, p4):
return self.isOrthogonal(p1, p2, p3) and self.isOrthogonal(p2, p3, p4) and self.isOrthogonal(p3, p4, p1)
def isRectangle(p1, p2, p3, p4):
return self._isRectangle(p1, p2, p3, p4) or self._isRectangle(p2, p3, p1, p4) or self._isRectangle(p1, p3, p2, p4)
|
一个更加巧妙地回答,我们可以先计算中点的位置

然后再计算中点到四个点的距离是不是一样即可。
?| 1 2 3 4 5 6 7 8 9 10 |
def dis(p1, p2):
return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2
def isRectangle(p1, p2, p3, p4):
x_c = (p1[0] + p2[0] + p3[0] + p4[0])/4
y_c = (p1[1] + p2[1] + p3[1] + p4[1])/4
d1 = dis(p1, (x_c,y_c))
d2 = dis(p2, (x_c,y_c))
d3 = dis(p3, (x_c,y_c))
d4 = dis(p4, (x_c,y_c))
return d1 == d2 and d1 == d3 and d1 == d4
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/tifosiboy/article/details/81604764








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。