C#平面随机非碰撞圆间矩形总面积计算异常排查
问题:C#控制台程序矩形总面积计算异常
我正在开发一个C#控制台程序,功能是在200×200的平面(x、y坐标范围为[-100+r, 100-r])内生成n个点作为半径为r的非碰撞圆的圆心,创建圆之间互不相交、不重叠的矩形集,并计算这些矩形的总面积。但程序输出结果在5000000到6000000之间,远超理论最大值。
我尝试将总面积除以200(因代码中比较的是距离平方),结果落在预期范围内,但不确定这是否是正确的修复方式(测试参数为N=867,r=2.0)。我怀疑问题可能出在以下代码部分,但无法确定:
public void GenerateRectangles() { var usedCenters = new HashSet<(double, double)>(); foreach (var point1 in circleCenters) { if (usedCenters.Contains(point1)) continue; foreach (var point2 in circleCenters) { if (point1 == point2 || usedCenters.Contains(point2)) continue; double dx = point2.x - point1.x; double dy = point2.y - point1.y; double distanceSquared = dx * dx + dy * dy; if (distanceSquared >= (2 * Radius) * (2 * Radius)) { double length = Math.Sqrt(distanceSquared) - 2 * Radius; double width = CalculateShortestDistance(point1, point2) - Radius; var rectangleCoords = CreateRectangle(point1, point2, width, length); rectangleBoundaries.Add((rectangleCoords, width * length)); totalAreaOfRectangles.Add(width * length); usedCenters.Add(point1); usedCenters.Add(point2); break; } } } HandleRemainingPoints(usedCenters); } private double CalculateShortestDistance((double x, double y) point1, (double x, double y) point2) { double dx = point2.x - point1.x; double dy = point2.y - point1.y; return Math.Sqrt(dx * dx + dy * dy); } private List<(double x, double y)> CreateRectangle((double x, double y) point1, (double x, double y) point2, double width, double length) { double dx = point2.x - point1.x; double dy = point2.y - point1.y; double normalX = dy; // Normal vector components double normalY = -dx; double magnitude = Math.Sqrt(normalX * normalX + normalY * normalY); normalX /= magnitude; normalY /= magnitude; var point3 = (point1.x + normalX * width, point1.y + normalY * width); var point4 = (point2.x + normalX * width, point2.y + normalY * width); return new List<(double x, double y)> { point1, point2, point4, point3 }; }
另外也怀疑总面积计算部分,但该部分仅对列表中的数值求和,暂未发现问题:
public void CalculateTotalArea() { double totalArea = 0; foreach (var area in totalAreaOfRectangles) { totalArea += area; } Console.WriteLine("Total Area Occupied by Rectangles: " + totalArea); }
内容的提问来源于stack exchange,提问作者hard_work_exploiter
相关产品推荐
相关产品推荐

