2013-10-05 113 views
0

我是Java新手,我试图在站点字段中的变量之间获得距离,但似乎无法工作。阵列中变量之间的距离

public static void main(String[]args){ 
double[] stations = {10,20,30};{ 
for(int i=0;i<stations.length-2;i++){ 
    double distance=stations[i+1] + stations[i]; 
} 
+3

看来,你必须'substract'而不是'add' – nachokk

+0

请发表您的代码的预期(必需的)结果。 –

+0

距离通常是值的差异。 –

回答

2

你需要substract而不是add每一个之间计算距离。所以你需要两个for循环来获得所有组合。

例子:

public static void main(String args[]){ 

      int i =0; 
      int j=0; 
      double[] stations = {10,20,30}; 
      for(i=0;i<stations.length;i++){ 
       for(j=i+1;j<stations.length;j++){ 
       System.out.println("distance between station "+i+" and station "+j+" is "+ (stations[j] - stations[i])); 
       }    
      } 
} 

输出:

distance between station 0 and station 1 is 10.0 
distance between station 0 and station 2 is 20.0 
distance between station 1 and station 2 is 10.0 
+0

非常感谢 – Doris