2 回答

TA貢獻1851條經(jīng)驗 獲得超5個贊
我對您的代碼進行了一些更改
int[][] countries = { { -34, -7 }, { 76, -23 }, { -5, -20 }, { -56, 64 }, { 12, 56 } };
double maxDistance = 0;
for (int i = 0; i < countries.length - 1; ++i) {
int x1 = countries[i][0];
int y1 = countries[i][1];
for (int j = i; j < countries.length; ++j) { // first j will be i
int x2 = countries[j][0];
int y2 = countries[j][1];
double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
maxDistance = maxDistance < distance ? distance : maxDistance;
}
}
System.out.println(maxDistance);
輸出
158.09174551506476
注意我如何循環(huán)i和j,以及我如何定義x1, x2, y1, y2

TA貢獻1966條經(jīng)驗 獲得超4個贊
在 i 之后開始您的 j 因為您已經(jīng)將先前的索引與數(shù)組的其余部分進行了比較。而且,您是否定義了 x1、x2、y1、y2 變量?
這應(yīng)該有助于:
int[][] countries = {{-34,-7},{76,-23},{-5,-20},{-56,64},{12,56}};
double maxDistance = 0;
for(int i = 0; i < countries.length-1; ++i) {
for(int j = i+1; j < countries.length; ++j) { //do not create zero distance or duplicate pairings
//get your x1, x2, y1, y2 from countries[i] and countries[j]
double distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
//compare with maxDistance
//assign maxDistance if you find it greater than previous one and record the coordinates which produced this distance
}
}
如果有不清楚的地方或者我錯過了什么,請發(fā)表評論;)
添加回答
舉報