gpt4 book ai didi

c++ - 检查 4 个点是否构成一个正方形

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:11:38 26 4
gpt4 key购买 nike

<分区>

根据这篇文章的解决方案 here .似乎使用点 (1,0)、(-1,0)、(0,1) 和 (0,-1) 解决方案失败时应该返回这些点确实形成一个正方形。

也许我的实现有问题。这是我的代码:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class Solution {
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {

double x1 = p1[0], x2 = p2[0], x3 = p3[0], x4 = p4[0];
double y1 = p1[1], y2 = p2[1] , y3 = p3[1], y4 = p4[1];

double cx = (x1+x2+x3+x4)/4;
double cy = (y1+y2+y3+y4)/4;

double a1 = (cx - x1), a2 = (cy - y1);
double b1 = (cx - x2), b2 = (cy - y2);
double c1 = (cx - x3), c2 = (cy - y3);
double d1 = (cx - x4), d2 = (cy - y4);

double dd1 = a1*a1 + a2*a2;
double dd2 = b1*b1 + b2*b2;
double dd3 = c1*c1 + c2*c2;
double dd4 = d1*d1 + d2*d2;
double epsilon = 0.00001;

return abs(dd1 - dd2) < epsilon && abs(dd1 - dd3) < epsilon && abs(dd1 - dd4) < epsilon;
}
};



int main() {

vector<int> p1, p2, p3, p4;
p1.push_back(1);
p1.push_back(0);
p2.push_back(-1);
p2.push_back(0);
p3.push_back(0);
p3.push_back(1);
p4.push_back(0);
p4.push_back(-1);

Solution m;
bool x;
x = m.validSquare(p1,p2,p3,p4);
if(x == 1) {
cout << "Points form a square" << endl;
}
else {
cout << "Points do not form a square" << endl;
}

return 0;
}

链接中的解决方案肯定是正确的,但是出于某种原因,这四点我没有得到准确的返回。如果有人有任何建议,请告诉我。

更新:

遵循用户的建议。我改了几行。使用点 (0,0)、(5,0)、(5,4) 和 (0,4) 应该不会返回这些点可以构成正方形。不幸的是,我更新后的代码仍然返回这些点是一个正方形,所以我不确定问题出在哪里。

这是我的代码:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class Solution {
public:
bool isFloatEqual(double a, double b) {
double epsilon = 0.001;
return abs(a - b) < epsilon;
}
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {

double x1 = p1[0], x2 = p2[0], x3 = p3[0], x4 = p4[0];
double y1 = p1[1], y2 = p2[1] , y3 = p3[1], y4 = p4[1];

double cx = (x1+x2+x3+x4)/4;
double cy = (y1+y2+y3+y4)/4;

double a1 = (cx - x1), a2 = (cy - y1);
double b1 = (cx - x2), b2 = (cy - y2);
double c1 = (cx - x3), c2 = (cy - y3);
double d1 = (cx - x4), d2 = (cy - y4);

double dd1 = a1*a1 + a2*a2;
double dd2 = b1*b1 + b2*b2;
double dd3 = c1*c1 + c2*c2;
double dd4 = d1*d1 + d2*d2;

return isFloatEqual(dd1,dd2) && isFloatEqual(dd1, dd3) &&isFloatEqual(dd1, dd4);

}
};



int main() {

vector<int> p1, p2, p3, p4;
p1.push_back(0);
p1.push_back(0);
p2.push_back(5);
p2.push_back(0);
p3.push_back(5);
p3.push_back(4);
p4.push_back(0);
p4.push_back(4);

Solution m;
bool x;
x = m.validSquare(p1,p2,p3,p4);
if(x == 1) {
cout << "Points form a square" << endl;
}
else {
cout << "Points do not form a square" << endl;
}

return 0;
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com