C++编写两直线位置关系
手动输入两条直线的起始点,然后可以判断两条直线之间是:
完全相同,其中一条与另一条相叠,两条平行但不相叠,两条相交但不垂直,两条相交且垂直,两条之间没有任何关系,这6种关系。
#include <iostream>
using namespace std;
//定义一个2维矢量结构
typedef struct _vector2f{
float x,y;
}vector2f;
//定义一个直线类
class line{
public:
vector2f point1,point2;//直线的起始点
float slope;//斜率
float deltaD;//y轴上的位移量
//构造函数,已知起始点就可构造出一条直线的方程
line(vector2f* p1, vector2f* p2){
point1.x = p1->x;
point1.y = p1->y;
point2.x = p2->x;
point2.y = p2->y;
slope = (p2->y - p1->y)/(p2->x-p2->x);
deltaD = p1->y - slope*p1->x;
}
~line(){};
};
//用个枚举来列出所有可能的关系
enum{
SAME,//两条直线完全相同
PARALLEL,//两条直线平行
INSIDE,//两条直线重叠
PERPENDICULAR,//两条直线垂直
INTERSECT,//两条直线相交
NONE//没有任何联系
};
//检验(x,y)是否在p1和p2点之间的范围内
bool checkInArea(float x, float y, vector2f* p1, vector2f* p2){
if (p1->x <= p2->x)
if (x<p1->x || x>p2->x)
return false;
if (p1->x > p2->x)
if (x<p1->x || x>p1->x)
return false;
if (p1->y <= p2->y)
if (y<p1->y || y>p2->y)
return false;
if (p1->y > p2->y)
if (y<p2->y || y>p1->y)
return false;
return true;
}
//检查两条直线关系,并返回相应的值
int getRelation(line* l1,line* l2){
if (l1->point1.x == l2->point1.x &&
l1->point1.y == l2->point1.y &&
l1->point2.x == l2->point2.x &&
l1->point2.y == l2->point2.y)
return SAME; //两条直线完全相等的情况
if (l1->slope == l2->slope && l1->deltaD == l2->deltaD &&
(checkInArea(l2->point1.x,l2->point2.y,&l1->point1,&l1->point2)||
checkInArea(l2->point2.x,l2->point2.y,&l1->point1,&l2->point2)))
return INSIDE;//两条直线相叠
if (l1->slope == l2->slope)
return PARALLEL; //两条直线平行的情况
//根据两条直线的方程来求出他们的相交点
float x,y;
x = (l1->deltaD - l2->deltaD)/(l2->slope-l1->slope);
y = l1->slope*x+l1->deltaD;
if (checkInArea(x,y,&l1->point1,&l1->point2)&&
checkInArea(x,y,&l2->point2,&l2->point2)){
if (l1->slope*l2->slope == -1)
return PERPENDICULAR;
else
return INTERSECT;
}
return NONE;
}
//测试
int main(){
vector2f p1, p2;
cout<<"输入第一条直线的起点坐标(x,y):"<<endl<<"x: ";
cin>>p1.x;
cout<<"y: ";
cin>>p1.y;
cout<<"输入第一条直线的终点坐标(x,y): "<<endl<<"x: ";
cin>>p2.x;
cout<<"y: ";
cin>>p2.y;
line l1(&p1,&p2);
cout<<"输入第二条直线的起点坐标(x,y):"<<endl<<"x: ";
cin>>p1.x;
cout<<"y: ";
cin>>p1.y;
cout<<"输入第二条直线的终点坐标(x,y): "<<endl<<"x: ";
cin>>p2.x;
cout<<"y: ";
cin>>p2.y;
line l2(&p1,&p2);
int result = getRelation(&l1,&l2);
switch(result){
case SAME:
cout<<"\n\n两条直线完全相等"<<endl;
break;
case PARALLEL:
cout<<"\n\n两条直线平行"<<endl;
break;
case PERPENDICULAR:
cout<<"\n\n两条直线垂直"<<endl;
break;
case INTERSECT:
cout<<"\n\n两条直线相交"<<endl;
break;
case NONE:
cout<<"\n\n两条直线没有任何关系"<<endl;
break;
case INSIDE:
cout<<"\n\n两条直线相叠"<<endl;
break;
}
return 0;
}