您的位置:首页 > 编程语言 > C语言/C++

c++求两条直线的交点

2012-05-21 17:16 351 查看
百度知道上找的,先留着慢慢研究:

来源:http://zhidao.baidu.com/question/79460681.html

//.h文件
#ifndef _LINE_H_
#define _LINE_H_

#include <stdio.h>
#include <iostream.h>

class Point
{
public:
/* 点的坐标 */
int x1;
int y1;

public:
void SetXY(int x, int y);
void GetXY(int &x, int &y);

/* 2个构造函数 */
Point();
Point(int x, int y);
};

class Line : public Point /* line继承point */
{
public:
/* 另一个点的坐标 */
int x2;
int y2;

public:
void SetPoint(Point* point1, Point* point2);

/* 3个构造函数 */
Line();
Line(int x1, int y1, int x2, int y2);
Line(Point* point1, Point* point2);

/* 是否相交
** 相交返回0, 交点为intersect_point
** 不相交返回-1, intersect_point为空
** 两直线相同返回1, intersect_point为空
*/
int Intersect(Line* another_line, Point* intersect_point);
};

#endif

//.c文件
#include "1.h"

Point::Point()
{
x1 = 0;
y1 = 0;
}

Point::Point(int x, int y)
{
x1 = x;
y1 = y;
}

void Point::SetXY(int x, int y)
{
x1 = x;
y1 = y;
}

void Point::GetXY(int &x, int &y)
{
x = x1;
y = y1;
}

Line::Line()
{
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
}

Line::Line(int x1, int y1, int x2, int y2)
{
this->x1 = x1;
this->x2 = x2;
this->y1 = y1;
this->y2 = y2;
}

void Line::SetPoint(Point* point1, Point* point2)
{
x1 = point1->x1;
y1 = point1->y1;
x2 = point2->x1;
y2 = point2->y1;
}

Line::Line(Point* point1, Point* point2)
{
x1 = point1->x1;
y1 = point1->y1;
x2 = point2->x1;
y2 = point2->y1;
}

int Line::Intersect(Line* another_line, Point* intersect_point)
{
/* y = ax + b */
int a_my, b_my;
b_my = (x1 * y2 - y1 * x2) / (x1 - x2);
a_my = (y1 - y2) / (x1 - x2);

/* check if point */
Point* point = (Point*)another_line;
if(a_my * point->x1 + b_my == point->y1)
{
intersect_point = point;
return 0;
}

int a_other, b_other;
a_other = (another_line->x1 * another_line->y2 - another_line->y1 * another_line->x2) / (another_line->x1 - another_line->x2);
b_other = (another_line->y1 - another_line->y2) / (another_line->x1 - another_line->x2);

if(a_other == a_my)
{
if(b_my == b_other)
{
intersect_point = NULL;
return -1; //not intersect
}
else
{
return 1; //the same
}
}
else
{
intersect_point->x1 = ((b_other - b_my) / (a_my - a_other));
intersect_point->y1 = (a_my * intersect_point->x1 + b_my);
return 0; //intersect
}

}

/* test */
int main()
{
Point point1(0, 1);
Point point2(1, 2);

Line line1(0, 1, 1, 2);
Line line2(&point1, &point1);

Line po;
int a = line1.Intersect((Line*)&line2, &po);
if(a == 0)
{
cout<<"yes"<<endl;
cout<<"x = "<<po.x1<<", y = "<<po.y1<<endl;
}
else if(a == -1)
{
cout<<"no"<<endl;
}
else
{
cout<<"same"<<endl;
}

return 0;
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ class 百度 null