简体   繁体   中英

calculate the Euclidean distance between an array in c# with function

I want to calculate a euclidean distance between points that the user enter,so as you can see here :

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++)
    {

    }
}

在此输入图像描述

is there any function in c# that can do this ?

I need to have each distance value between all points in my array

Here is how to implement the distance calculation between two given points, to get you started:

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);

Try following

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)));    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM