gpt4 book ai didi

c# - 计算每个 x 和 y 坐标的距离

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:29 24 4
gpt4 key购买 nike

我正在编写一个函数来计算与 x 和 y 坐标的距离。我有一个二维数组,其中包含一堆 x 和 y 坐标。函数按距点的距离顺序返回 x 和 y 坐标列表。要计算与每个点的距离,有一个公式(坐标总和的平方根)。

我可以计算每个 x 和 y 坐标的距离。我正在将其添加到列表中。我如何将距离存储为特定坐标的另一个属性,然后对其进行排序。

public static List<List<int>> calculateDistance(int[,] Coordinates)
{
List<List<int>> result = new List<List<int>>();
int bound0 = Coordinates.GetUpperBound(0);
List<double> distance = new List<double>();

for (int i = 0;i <= bound0; i++)
{
distance.Add(Math.Sqrt(Coordinates[i, 0]) + Coordinates[i,1]));
}

return result;
}
}

最佳答案

根据您的描述,您不需要创建 calculateDistance 方法。计算距离的公式可以用 lambda 表达式给出。您可以在代码中的任何位置创建所需的列表并使用 Linq 对其进行排序。

例子

var list = Enumerable
.Range(0, Coordinates.GetLength(0))
.Select(i => new { X = Coordinates[i, 0], Y = Coordinates[i, 1], D = Math.Sqrt(Math.Pow(Coordinates[i, 0], 2) + Math.Pow(Coordinates[i, 1], 2)) });

Math.Sqrt(Math.Pow(Coordinates[i, 0], 2) + Math.Pow(Coordinates[i, 1], 2))这里用来演示.而是使用您自己的表达式来计算距离。

要对此进行排序,您可以简单地使用

var list2 = list.OrderBy(a => a.D);

关于c# - 计算每个 x 和 y 坐标的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com