判斷四個點是否爲正方形

//要考慮正方形是傾斜的情況
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
struct point
{
    double x, y;
} a[4];
bool cmp(point a, point b)
{
    if (a.x != b.x)
        return a.x < b.x; //如果,橫座標不相等,所有點按橫座標升序排列
    return a.y < b.y;//如果橫座標相等,所有點按縱座標升序排列
}
double TwoPointDiatance(point a, point b)//計算兩點之間的距離
{
    return sqrt(pow((a.x - b.x), 2) + pow((a.y - b.y), 2));
}
bool IsRightAngle(point a, point b, point c)//判斷是否爲直角
{
    double x;
    x = (a.x - b.x)* (a.x - c.x) + (a.y - b.y)*(a.y - c.y);
    if (x < 0.00001)
        return 1;
    else
        return 0;
}
int main()
{
    double s1, s2, s3, s4;
    for (int i = 0; i < 4; i++)
        cin >> a[i].x >> a[i].y;
    //確定點,排序,給點確定標號
    sort(a, a + 4, cmp);
    //確定邊
    s1 = TwoPointDiatance(a[0], a[2]);
    s2 = TwoPointDiatance(a[0], a[1]);
    s3 = TwoPointDiatance(a[3], a[1]);
    s4 = TwoPointDiatance(a[2], a[3]);
    //分析是否爲正方形
    if (s1 == s2&&s3 == s4&&s1 == s2&&s1 != 0 && IsRightAngle(a[0], a[1], a[2]))//三個條件同時滿足(1:四條邊相等,2:邊不爲0,3:有一個直角)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章