方法一:代数法。
对于l1,l2求出方程ax+by+c=0
解方程求交点。
方法二:几何法。
利用面积比值推出线段比值
再用相似三角形,进行向量放缩就可以了。
#include <iostream> #include <cmath> using namespace std; const double eps=1e-8; struct Tpoint { double x,y; Tpoint(){} Tpoint(double _x,double _y){x=_x,y=_y;} void print() { printf("%.3lf %.3lf\n",x,y); } }; struct Tline { Tpoint p1,p2; double a,b,c; Tline(){} Tline(double x1,double y1,double x2,double y2){p1=Tpoint(x1,y1),p2=Tpoint(x2,y2);} void init() { a=p1.y-p2.y; b=p2.x-p1.x; c=p1.x*p2.y-p2.x*p1.y; } }; int sig(double x) { if(fabs(x)<=eps)return 0; if(x>eps)return 1;else return -1; } Tpoint operator -(Tpoint p1,Tpoint p2) { return Tpoint(p1.x-p2.x,p1.y-p2.y); } Tpoint operator *(Tpoint p,double a) { p.x*=a,p.y*=a; return p; } double operator *(Tpoint p1,Tpoint p2) { return p1.x*p2.y-p2.x*p1.y; } Tpoint operator +(Tpoint p1,Tpoint p2) { return Tpoint(p1.x+p2.x,p1.y+p2.y); } Tpoint lineintersect1(Tline l1,Tline l2) { double ta=(l1.p2-l2.p1)*(l1.p1-l2.p1); double tb=(l2.p2-l1.p2)*(l1.p1-l1.p2); Tpoint tp; tp=(l2.p2-l2.p1)*(ta/(ta+tb))+l2.p1; return tp; } Tpoint lineintersect2(Tline l1,Tline l2) { Tpoint p; double tp=l1.b*l2.a-l1.a*l2.b; if(sig(tp)==0)return p; p.x=(-l1.c*l2.b+l1.b*l2.c)/(-tp); p.y=(-l1.c*l2.a+l1.a*l2.c)/tp; return p; } int main() { freopen("tmp.in","r",stdin); freopen("tmp.out","w",stdout); Tline l1,l2; double x1,x2,y1,y2; scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2); l1=Tline(x1,y1,x2,y2);l1.init(); scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2); l2=Tline(x1,y1,x2,y2);l2.init(); Tpoint p1=lineintersect1(l1,l2); Tpoint p2=lineintersect2(l1,l2); p1.print(),p2.print(); return 0; }