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