求两条直线的交点,运用面向对象的思想编程实现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))));
		}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值