C# で 2 点間の距離を計算する
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp Math
このチュートリアルでは、C# で 2 点間の距離を計算する方法について説明します。
C# のユークリッド距離式を使用して 2 点間の距離を計算する
ユークリッド距離の式は、2 点間の距離を計算するために使用されます。式は
です。
d は、それぞれポイント間の距離、p と q です。Math クラスを使用して、C# の座標の平方根と平方根を取得できます。Math.Pow() 関数は、パラメータとして 2 を渡すことにより、数値の 2 乗を計算します。Math.Sqrt() 関数は数値の平方根を計算します。したがって、C# で var distance = Math.Sqrt((Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2))); ステートメントを使用してユークリッド距離の式を適用できます。次のコード例は、C# のユークリッド距離の式を使用して 2 点間の距離を計算する方法を示しています。
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 の座標。ユークリッド距離の式を使用してこれらのポイント間の距離を計算し、結果を表示しました。
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 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