1. 程式人生 > >求兩條直線的交點,運用面向物件的思想程式設計實現C++原始碼

求兩條直線的交點,運用面向物件的思想程式設計實現C++原始碼

一般方程法:

直線的一般方程為F(x) = ax + by + c = 0。既然我們已經知道直線的兩個點,假設為(x0,y0), (x1, y1),那麼可以得到a = y0 – y1, b = x1 – x0, c = x0y1 – x1y0

因此我們可以將兩條直線分別表示為

F0(x) = a0*x + b0*y + c0 = 0, F1(x) = a1*x + b1*y + c1 = 0

那麼兩條直線的交點應該滿足

a0*x + b0*y +c0 = a1*x + b1*y + c1

由此可推出

x = (b0*c1 – b1*c0)/D

y = (a1*c0 – a0*c1)/D

D = a0*b1 – a1*b0

 (D0時,表示兩直線平行)

二者實際上就是連立方程組F0(x) = a0*x + b0*y + c0 = 0, F1(x) = a1*x + b1*y + c1 = 0的叉積應用

i     j     k

a0 b0 c0

a1 b1 c1

此方法摘自 http://blog.csdn.net/abcjennifer/article/details/7584628,本人親自推演過。

#include<iostream>
#include<iomanip>
using namespace std;

#define N  6
class Point{
public:
	double m_pointX;
	double m_pointY;
public:
	Point(){}
	Point(double x, double y){m_pointX = x; m_pointY = y;}
};

class Line:public Point{
public:
	double a;
	double b;
	double c;
public:
	Line GetLine(Point ptSource, Point ptDestination);
	Point GetCrossPoint(Line l1, Line l2);
	void CrossPointShow(Point ptCross);
};

Line Line::GetLine(Point ptSource, Point ptDestination)
{
	Line lTemp;
	lTemp.a = ptSource.m_pointY - ptDestination.m_pointY;  
    lTemp.b = ptDestination.m_pointX - ptSource.m_pointX;  
    lTemp.c = ptSource.m_pointX*ptDestination.m_pointY - ptDestination.m_pointX*ptSource.m_pointY;
	return lTemp;
}

Point Line::GetCrossPoint(Line l1, Line l2)
{
	Point pTemp;
	double D;
    D = l1.a*l2.b - l2.a*l1.b;  
    Point p;  
    pTemp.m_pointX = (l1.b*l2.c - l2.b*l1.c)/D;  
    pTemp.m_pointY = (l1.c*l2.a - l2.c*l1.a)/D;  
    return pTemp;
}

void Line::CrossPointShow(Point ptCross)
{
	cout<<"兩條直線交點的橫座標:"<<setprecision(N)<<ptCross.m_pointX<<endl;
	cout<<"兩條直線交點的縱座標:"<<setprecision(N)<<ptCross.m_pointY<<endl;
}

void main()
{
		Line l;
		double x0, x1, x2, x3, y0, y1, y2, y3;
		char c0, c1, d0;
		while (1)
		{
			cout<<"請輸入一條直線的兩點座標:"<<endl;
			cin>>c0>>x0>>d0>>y0>>c1>>c0>>x1>>d0>>y1>>c1;
			cout<<"請輸入另一條直線的兩點座標:"<<endl;
			cin>>c0>>x2>>d0>>y2>>c1>>c0>>x3>>d0>>y3>>c1;
			l.CrossPointShow(l.GetCrossPoint(l.GetLine(Point(x0, y0), Point(x1, y1)), l.GetLine(Point(x2, y2), Point(x3, y3))));
		}
}