用函数计算c#中数组之间的欧氏距离

时间:2016-01-09 20:37:29

标签: c# distance

我想计算用户输入的点之间的欧氏距离,如下所示:

static void Main(string[] args)
{
    int numtest = int.Parse(Console.ReadLine());
    int[,] points=new int[10,2];
    for (int i = 0; i < numtest; i++)
    {
        Console.WriteLine("point " +(i+1).ToString()+" x: ");
        points[i, 0] = int.Parse(Console.ReadLine());
        Console.WriteLine("point " + (i + 1).ToString() + " y: ");
        points[i, 1] = int.Parse(Console.ReadLine());
    }
}

public float[] calculate(int[,] points)
{
    for (int i = 0; i <points.Length ; i++)
    {

    }
}

enter image description here

c#中有没有可以执行此操作的功能?

我需要在数组中的所有点之间设置每个距离值

2 个答案:

答案 0 :(得分:6)

以下是如何实现两个给定点之间的距离计算,以帮助您入门:

int x0 = 0;
int y0 = 0;

int x1 = 100;
int y1 = 100;

int dX = x1 - x0;
int dY = y1 - y0;
double distance = Math.Sqrt(dX * dX + dY * dY);

答案 1 :(得分:4)

尝试以下

public void calculate(double[,] points)
{
    var distanceArray = new double[points.Length, points.Length];

    for (int i = 0; i < points.Length; i++)
        for (int j = 0; j < points.Length; j++)
            distanceArray[i, j] = Distance(points[i, 0], points[i, 1], points[j, 0], points[j, 1]);
}

public static double Distance(double x1, double y1, double x2, double y2)
=>  Math.Sqrt(((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));