判断四个点是否能构成正方形

代码:

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

struct point
{
	double x, y;
} a[4];

bool Compare(point a, point b)
{
	if (a.x != b.x)
		return a.x < b.x; //如果,横坐标不相等,所有点按横坐标升序排列
	return a.y < b.y;//如果横坐标相等,所有点按纵坐标升序排列
}

double dis(point a, point b)//计算两点之间的距离
{
	return sqrt((a.x - b.x)*(a.x - b.x)) + (a.y - b.y)*(a.y - b.y));
}

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()
{
	int n, k;
	double s1, s2, s3, s4;

	scanf("%d",&n);

	while (n--)
	{
		for (int i = 0; i < 4; i++)
			cin >> a[i].x >> a[i].y;

		//确定点,排序,给点确定标号
		sort(a, a + 4, Compare);

		//确定边
		s1 = dis(a[0], a[2]);
		s2 = dis(a[0], a[1]);
		s3 = dis(a[3], a[1]);
		s4 = dis(a[2], a[3]);

		//分析是否为正方形
		if (s1 == s2&&s3 == s4&&s1 != 0 && IsRightAngle(a[0], a[1], a[2]))//三个条件同时满足(1:四条边相等,2:边不为0,3:有一个直角)
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
		cout << endl;
		
	}

	return 0;
}

从文件中读取数据的代码如下:
在test.txt中第一行数据为表明有几例测试数据,接下来的每一行为一个坐标点的x,y坐标。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;

typedef struct point{
int x;
int y;

};


double dis(point c,point d){
return (sqrt((c.x-d.x)*(c.x-d.x)+(c.y-d.y)*(c.y-d.y)));

}

bool isrectangle(point u,point v,point w){
double wucha=(u.x-v.x)*(u.x-w.x)+(u.y-v.y)*(u.y-w.y);
if(wucha<0.00001){
    return true;
}
else{
    return false;
}
}

bool compare(point c,point d){
if(c.x==d.x){
    return c.y<d.y;
}
else{
    return c.x<c.x;
}
}

int main(){
    point a[4];
FILE *fp;
fp=fopen("A:\\test.txt","rw+");
while(!feof(fp)){
    int n;
    fscanf(fp,"%d",&n);
    for(int i=0;i<n;i++){
        fscanf(fp,"%d",&a[0].x);
        fscanf(fp,"%d",&a[0].y);
        fscanf(fp,"%d",&a[1].x);
        fscanf(fp,"%d",&a[1].y);
        fscanf(fp,"%d",&a[2].x);
        fscanf(fp,"%d",&a[2].y);
        fscanf(fp,"%d",&a[3].x);
        fscanf(fp,"%d",&a[3].y);

        sort(a,a+4,compare);

        double b[4];
        b[0]=dis(a[0],a[1]);
        b[1]=dis(a[0],a[2]);
        b[2]=dis(a[1],a[3]);
        b[3]=dis(a[2],a[3]);
        if(b[0]==b[1]&&b[1]==b[2]&&b[2]==b[3]&&b[3]==b[0]){
            if(isrectangle(a[0],a[1],a[2])){
                printf("YES\n");
            }
            else{
                printf("NO\n");
            }

        }
        else{
            printf("NO\n");
        }


    }


}

return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值