gpt4 book ai didi

java - 数组中变量之间的距离

转载 作者:行者123 更新时间:2023-12-02 06:40:25 25 4
gpt4 key购买 nike

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

最佳答案

您需要减去而不是来计算每个点之间的距离。因此,您需要两个 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

关于java - 数组中变量之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19201948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com