数组中变量之间的距离

时间:2013-10-05 19:45:24

标签: java arrays distance

我是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];
}

1 个答案:

答案 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