C#直线和直线的交点和距离

C#直线和直线的交点和距离,第1张

C#实现直线和直线的交点和距离

由于直线程序计算中可能会出现误差,这里的 a==b均用 a-b<0.001 代替

  public static double InterL2L(double a1, double b1, double c1, double a2, double b2, double c2, out double x, out double y)
        {
            double distance = 0;
            if (Math.Abs(a1 - a2) < 0.001 && Math.Abs(b1 - b2) < 0.001) //平行线
            {
                x = 0;
                y = 0;   
                distance = Math.Abs(c1 - c2) / Math.Sqrt(a1 * a1 + b1 * b1);
            }
            else if (b1 == 0 && b2 == 0) //两条垂线
            {
                x = 0;
                y = 0;

                distance = Math.Abs((-c1 / a1) + (c2 / a2));
            }
            else if (a1 == 0 && a2 == 0) //两条水平线
            {
                x = 0;
                y = 0;
                distance = Math.Abs((-b1 / a1) + (b2 / a2));
            }
            else if (a1 == 0 && b1 == 0) //线1不存在
            {
                x = 0;
                y = 0;
            }
            else if (a2 == 0 && b2 == 0)//线2不存在
            {
                x = 0;
                y = 0;
            }
            else if (a1 == 0 && b2 == 0)//线1水平,线2垂直
            {
                x = -c2 / a2;
                y = -c1 / b1;
            }
            else if (a2 == 0 && b1 == 0)//线2水平,线1垂直
            {
                x = -c1 / a1;
                y = -c2 / b2;
            }
            else if (a1 == 0)//线1水平
            {
                y = -c1 / b1;
                x = -(b2 * y + c2) / a2;
            }
            else if (a2 == 0)//线2水平
            {
                y = -c2 / b2;
                x = -(b1 * y + c1) / a1;
            }
            else if (b1 == 0) //线1垂直
            {
                x = -c1 / a1;
                y = -(a2 * x + c2) / b2;
            }
            else if (b2 == 0)//线2垂直
            {
                x = -c2 / a2;
                y = -(a1 * x + c1) / b1;
            }
            else
            {
				//double d1;
            	//double e1;
            	//double d2;
            	//double e2;
            	double b;
            	double c;
            	
                //d1 = b1 / a1;
                //e1 = c1 / a1;

                //d2 = b2 / a2;
                //e2 = c2 / a2;

                b = (b2 / a2) - (b1 / a1);
                c = (c2 / a2) - (c1 / a1);
                y = -c / b;
                x = -(b1 * y + c1) / a1;
            }
            return distance;
        }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/707237.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存