永发信息网

求两条直线的交点!! C++

答案:1  悬赏:0  手机版
解决时间 2021-11-17 07:14
  • 提问者网友:伴风望海
  • 2021-11-16 07:01
求两条直线的交点!! C++
最佳答案
  • 五星知识达人网友:夜余生
  • 2021-11-16 08:29
代码和注释给你, 自己整理吧

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

#include
#include

class Point
{
public:

int x1;
int y1;

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


Point();
Point(int x, int y);
};

class Line : public Point
{
public:

int x2;
int y2;

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


Line();
Line(int x1, int y1, int x2, int y2);
Line(Point* point1, Point* point2);


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)
{

int a_my, b_my;
b_my = (x1 * y2 - y1 * x2) / (x1 - x2);
a_my = (y1 - y2) / (x1 - x2);


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
}

}


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"< cout<<"x = "< }
else
{
cout<<"same"< }

return 0;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯