[CSharpTips]C# 判断一个点是否在线段上
C# 判断一个点是否在线段上
using System; using System.Collections.Generic; using System.Windows; namespace PointInLineTest { class Program { static void Main(string[] args) { List<Point> points = new List<Point>(); points.Add(new Point(97.513, 5.076)); points.Add(new Point(103.589, 11.153)); points.Add(new Point(131.885, 39.449)); var result = GetPointIsInLine(points[1], points[0], points[2], 0.001); Console.WriteLine(result); Console.ReadLine(); } /// <summary> /// 判断点是否在线段上 /// </summary> /// <param name="pf">判断点</param> /// <param name="p1">线段起点</param> /// <param name="p2">线段终点</param> /// <param name="range">判断的的误差,不需要误差则赋值0</param> /// <returns></returns> public static bool GetPointIsInLine(Point pf, Point p1, Point p2, double range) { //点在线段首尾两端之外则return false double cross = (p2.X - p1.X) * (pf.X - p1.X) + (p2.Y - p1.Y) * (pf.Y - p1.Y); if (cross <= 0) return false; double d2 = (p2.X - p1.X) * (p2.X - p1.X) + (p2.Y - p1.Y) * (p2.Y - p1.Y); if (cross >= d2) return false; double r = cross / d2; double px = p1.X + (p2.X - p1.X) * r; double py = p1.Y + (p2.Y - p1.Y) * r; //判断距离是否小于误差 return Math.Sqrt((pf.X - px) * (pf.X - px) + (py - pf.Y) * (py - pf.Y)) <= range; } } }
运行结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了