C# 求两个线段之间的夹角

如下图所示,在△ABC中,余弦定理可表示为:
同理,也可描述为:
勾股定理是余弦定理的特例。
   
   
时,
   
,余弦定理可简化为
   
,即勾股定理。
/// <summary>  
/// 根据余弦定理求两个线段夹角  
/// </summary>  
/// <param name="o">端点</param>  
/// <param name="s">start点</param>  
/// <param name="e">end点</param>  
/// <returns></returns>  
double Angle(PointF o, PointF s, PointF e)  
{  
    double cosfi = 0, fi = 0, norm = 0;  
    double dsx = s.X - o.X;  
    double dsy = s.Y - o.Y;  
    double dex = e.X - o.X;  
    double dey = e.Y - o.Y;  
  
    cosfi = dsx * dex + dsy * dey;  
    norm = (dsx * dsx + dsy * dsy) * (dex * dex + dey * dey);  
    cosfi /= Math.Sqrt(norm);  
  
    if (cosfi >= 1.0) return 0;  
    if (cosfi <= -1.0) return Math.PI;  
    fi = Math.Acos(cosfi);  
  
    if (180 * fi / Math.PI < 180)  
    {  
        return 180 * fi / Math.PI;  
    }  
    else  
    {  
        return 360 - 180 * fi / Math.PI;  
    }  
}  


  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
两个线段的交点,可以使用以下步骤来实现: 1. 首先,定义一个表示线段的结构体或类。可以使用两个点来表示线段的起点和终点。 ```csharp public struct LineSegment { public Point StartPoint { get; set; } public Point EndPoint { get; set; } } ``` 2. 编写一个函数来计算两个线段的交点。可以使用线段的参数方程来解。 ```csharp public static Point? GetIntersectionPoint(LineSegment line1, LineSegment line2) { // 获取线段1的参数 double x1 = line1.StartPoint.X; double y1 = line1.StartPoint.Y; double x2 = line1.EndPoint.X; double y2 = line1.EndPoint.Y; // 获取线段2的参数 double x3 = line2.StartPoint.X; double y3 = line2.StartPoint.Y; double x4 = line2.EndPoint.X; double y4 = line2.EndPoint.Y; // 计算分母 double denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); // 当分母为0时,表示两线段平行或重合,没有交点 if (denominator == 0) return null; // 计算交点的坐标 double x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denominator; double y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denominator; // 检查交点是否在两个线段上 if (x < Math.Min(x1, x2) || x > Math.Max(x1, x2) || x < Math.Min(x3, x4) || x > Math.Max(x3, x4) || y < Math.Min(y1, y2) || y > Math.Max(y1, y2) || y < Math.Min(y3, y4) || y > Math.Max(y3, y4)) return null; return new Point(x, y); } ``` 3. 创建两个线段对象,然后调用函数获取交点。 ```csharp LineSegment line1 = new LineSegment { StartPoint = new Point(0, 0), EndPoint = new Point(10, 10) }; LineSegment line2 = new LineSegment { StartPoint = new Point(0, 10), EndPoint = new Point(10, 0) }; Point? intersectionPoint = GetIntersectionPoint(line1, line2); if (intersectionPoint.HasValue) { Console.WriteLine($"Intersection point: ({intersectionPoint.Value.X}, {intersectionPoint.Value.Y})"); } else { Console.WriteLine("No intersection point."); } ``` 这样,你就可以两个线段的交点了。注意,如果两个线段平行或重合,将会返回 null。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值