【发布时间】:2019-01-20 20:30:27
【问题描述】:
所以我在二维数组中有一组元素,我正在尝试确定坐标之间的最大距离。
我已经创建了一个循环来遍历每个元素,但我无法弄清楚如何只比较第一组,第二组等等。这几天我一直在尝试不同的方法,这就是我到目前为止所得到的。
使用公式: farthestDistance = Math.sqrt((Math.pow((maxX - minX), 2))+ (Math.pow((maxY-minY), 2)));
int max = cities[0][0]; //int to store the max of the i column
int min = cities[0][0]; //int to store the max of the i column
int maxX = cities[0][0]; //int to store the max of the i column
int maxY = cities[0][0]; //int to store the max of the i column
int minX = cities[0][0]; //int to store the max of the j column
int minY = cities[0][0]; //int to store the max of the j column
for(int y=1; y<cities[0].length; y++) { //loop through columns
for(int x=0; x<cities[y].length; x++) { //loop through lines
if(cities[x][y] > max) { //if the number at the column i and line j is bigger than max
max = cities[x][y];
maxX = cities[x][0];
maxY = cities[0][y];
}
if(((cities[x][0]) < min) && (cities[0][y] < min)) { //if the number at the column i and line j is bigger than max
min = cities[x][y];
minX = cities[x][0];
minY = cities[0][y];
}
}
}
System.out.println("the maxX is " +maxX+ " the minX is " + maxY);
System.out.println("the maxX is " +minX+ " the minX is " + minY);
}
}
对于我拥有的示例数组:
int[][] 城市 = {{-48,-4},{23,-45},{-7,-40},{-28,31},{36,24},{23,-11} ,{36,-10},{-9,21}};
并且预期的输出应该是大约 91.5259。 任何帮助/指导将不胜感激!
【问题讨论】:
标签: java arrays multidimensional-array euclidean-distance