已知四個點的坐標,判斷四個點能否連成一個正方形


思路:根據正方形的特性,四條邊相等,兩條對角線相等,所以只需要計算四點兩兩之間的距離,然后判斷是否有且僅有兩種長度的距離,就能判斷這四個點是否能連成正方形。

C++代碼如下:首先需要輸入要測試的組數,然后依次輸入兩組數字,分別對應點的x坐標和y坐標,如果能連成正方形則輸出“Yes”,否則輸出“No”。

輸入:

2

0 0 1 0

0 1 0 1

1 2 3 4

2 2 3 3

輸出:

Yes

No

#include<iostream>
#define LEN 6
using namespace std;

bool inArray(int arr[], int num) {
    for (int i = 0; i<LEN; i++) {
        if (arr[i] == num)
            return true;
    }
    return false;
}
int main() {
    int t = 0;
    int x[4], y[4];
    int len[6];
    cin >> t;
    while (t>5 || t<1) {
        cin >> t;
    }
    int cnt;
    int length;
    while (t--) {
        cnt = 0;
        cin >> x[0] >> x[1] >> x[2] >> x[3];
        cin >> y[0] >> y[1] >> y[2] >> y[3];
        for (int i = 0; i < 4; i++) {
            for (int j = 1; j < (4 - i); j++) {
                length = (x[i] - x[i + j])*(x[i] - x[i + j]) + (y[i] - y[i + j])*(y[i] - y[i + j]);
                if (!inArray(len, length)) {
                    len[cnt] = length;
                    cnt++;
                }
            }
        }
        if (cnt == 2)
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM