在 C# 中计算 2 点之间的距离
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp Math
本教程将讨论在 C# 中计算两点之间的距离的方法。
在 C# 中用欧氏距离公式计算 2 点之间的距离
欧几里得距离公式用于计算 2 个点之间的距离。该公式为
。
d 是点之间的距离,分别是 p 和 q。我们可以使用 Math 类来获取 C# 中坐标的平方和平方根。Math.Pow()函数](https://learn.microsoft.com/zh-cn/dotnet/api/system.math.pow?view=net-5.0/)通过将 2 作为参数来计算数字的平方。[Math.Sqrt()函数计算数字的平方根。因此,我们可以在 C# 中的 var distance = Math.Sqrt((Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2)); 语句应用欧几里德距离公式。下面的代码示例向我们展示了如何使用 C# 中的欧几里得距离公式来计算两点之间的距离。
using System;
namespace measure_distance {
class Program {
static void Main(string[] args) {
double x1, x2, y1, y2;
x1 = 12d;
x2 = 13d;
y1 = 11d;
y2 = 10d;
var distance = Math.Sqrt((Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2)));
Console.WriteLine(distance);
}
}
}
输出:
1.4142135623731
在上面的代码中,我们初始化了点 1 和点 2 的 x 和 y 坐标。变量 x1 和 y1 是点 1 的坐标,变量 x2 和 y2 是点 2 的坐标。我们使用欧几里得距离公式计算了这些点之间的距离,并显示了结果。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn