我有一个问题,我需要帮助解决。我应该创建一个计算两个位置之间距离的函数。位置存储在两个数组中,我可以使用我需要的多个参数进行此计算
static double[] Latitudes = new double[] {
59.3261917, 57.7010496, 59.8939529, 65.5867395, 60.11021, 52.5069312, 48.859
};
static double[] Longitudes = new double[] {
17.7018773, 11.6136602, 10.6450348, 22.0422998, 24.7385057, 13.1445521, 2.2069765
};
我得到了一个可以帮助我计算距离的等式
distance = Math.sqrt( (x1 - x2)2 + (y1 - y2)2 )
我的问题是我无法将数组中的元素转换为函数内的变量
答案 0 :(得分:2)
首先,您需要确定要比较的位置。这将通过索引完成。让我们说你想比较索引0
的位置和索引2
的位置。然后获取正确变量的代码是:
double x1 = Latitudes[0];
double y1 = Longitudes[0];
double x2 = Latitudes[2];
double y2 = Longitudes[2];
然后,您可以将这些值提供给您的函数。您的功能代码错误,无法编译。正确调用该函数将是:
double distance = Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));
为了为您的班级提供更完整的功能,并记住您的阵列是静态的,这将允许您根据索引获得任意两个给定点的距离。另外,我希望这是一个家庭作业,所以我倾向于你要求创建一个类似于此的功能:
double CalculateDistance(int index1, int index2)
{
double x1 = Latitudes[index1];
double y1 = Longitudes[index1];
double x2 = Latitudes[index2];
double y2 = Longitudes[index2];
return Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));
}
然后您可以按如下方式调用此函数:
double distance = CalculateDistance(0, 2);
答案 1 :(得分:2)
提取方法,将问题分成次要:
// Initial step:
// Distance between points
private static double Distance(double x1, double y1, double x2, double y2) {
return Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
// Next step:
// Distance between points given as arrays' items indexes
private static double Distance(double[] xs, double[] ys, int indexFrom, indexTo) {
return Distance(xs[indexFrom], ys[indexFrom], xs[indexTo], ys[indexTo]);
}
然后使用
// What is the distance between 0-th and 2-nd point?
double result = Distance(Latitudes, Longitudes, 0, 2);
Console.WriteLine(result);
// What is the distance between all the points?
for (int from = 0; from < Math.Min(Latitudes.Length, Longitudes.Length); ++from)
for (int to = from + 1; to < Math.Min(Latitudes.Length, Longitudes.Length); ++to) {
Console.WriteLine($"Distance from item #{from} to item #{to} is {Distance(Latitudes, Longitudes, from, to)}");
}
答案 2 :(得分:1)
显示所有对的小说
if (Latitudes.Length == Longitudes.Length)
{
for (int i = 0; i < Latitudes.Length - 1; i = i + 2)
{
double x1 = Longitudes[i];
double x2 = Longitudes[i + 1];
double y1 = Latitudes[i];
double y2 = Latitudes[i + 1];
double distance = Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));
Console.WriteLine($"x1 = {x1}; x2 = {x2}; y1 = {y1}; y2 = {y2}; distance {distance}");
}
}