利用叉积解方程
#include <cstdio> #define MAX 1<<31 #define dd double int xmult(dd x1,dd y1,dd x2,dd y2,dd x,dd y){ return (x1-x)*(y2-y)-(x2-x)*(y1-y); } int main(){ int n; dd x1,y1,x2,y2,x3,y3,x4,y4; scanf("%d",&n); puts("INTERSECTING LINES OUTPUT"); while(n--){ scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4); dd a1=y1-y2; dd b1=x2-x1; dd c1=xmult(x1,y1,x2,y2,0,0); dd a2=y3-y4; dd b2=x4-x3; dd c2=xmult(x3,y3,x4,y4,0,0); if(a1*b2==a2*b1){ if(xmult(x1,y1,x2,y2,x3,y3)==0) puts("LINE"); else puts("NONE"); } else { dd cx,cy; cx=(b1*c2-c1*b2)/(a1*b2-a2*b1); cy=(a1*c2-c1*a2)/(b1*a2-b2*a1); printf("POINT %.2f %.2f\n",cx,cy); } } puts("END OF OUTPUT"); }
利用点斜式解方程
#include <cstdio> #define MAX 1<<31 #define dd double struct P{ dd x,y; void input(){ scanf("%lf%lf",&x,&y); } void output(){ printf("POINT %.2f %.2f\n",x,y); } }; struct L{ P s,e; void input(){ s.input(),e.input(); } dd k(){ if(s.x==e.x)return MAX; return (s.y-e.y)/(s.x-e.x); } }l1,l2; int xmult(P a,P b,P o){ return (a.x-o.x)*(b.y-o.y)-(b.x-o.x)*(a.y-o.y); } void getCross(L a,L b){ P c; dd ka=a.k(),kb=b.k(); if(ka==MAX){//a是竖直的 c.x=a.s.x; c.y=(c.x-b.s.x)*kb+b.s.y; } else{ if(kb==MAX) c.x=b.s.x; else c.x=(a.s.y-b.s.y-ka*a.s.x+kb*b.s.x)/(kb-ka); c.y=(c.x-a.s.x)*ka+a.s.y; } c.output(); } int main(){ int n; scanf("%d",&n); puts("INTERSECTING LINES OUTPUT"); while(n--){ l1.input(),l2.input(); dd ka=l1.k(),kb=l2.k(); if(ka==kb){ if(xmult(l1.s,l1.e,l2.s)==0) puts("LINE"); else puts("NONE"); } else getCross(l1,l2); } puts("END OF OUTPUT"); }
时间: 2024-11-08 13:58:46