gpt4 book ai didi

java - 被告知我的代码不是递归...寻找指导为什么不!

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

有人向我指出下面的语句不是递归。我认为递归仅意味着它调用自身直到找到答案。什么会导致这个递归?

public static double totalDistance(int[] x, int[] y, String[] city, int i){

double xSub = x[i] - x[i-1];
double ySub = y[i] - y[i-1];
double distance = Math.pow(xSub, 2) + Math.pow(ySub, 2);
distance = Math.round(Math.sqrt(distance));
System.out.println("Distance From " + city[i] + " to " + city[i-1] + " is " + distance + " miles.");

if (i == 1){
return distance;
}
else {
return distance+totalDistance(x,y,city, i-1);
}
}
<小时/>

这是下面的完整代码,以防有人对发生的事情感到好奇......

import java.util.Scanner;
class distance {


public static void main(String[] args) {

System.out.println("Welcome to Travel Bliss Distance Calculator!");
Scanner input = new Scanner(System.in);
int[] x = new int[5];
int[] y = new int[5];
String[] city = new String[5];


int i=0;
for (i=0; i < 5;i++){
System.out.println("Enter City>>");
city[i] = input.next();
System.out.println("Enter X Coordinates>>");
x[i] = input.nextInt();
System.out.println("Enter Y Coordinates>>");
y[i] = input.nextInt();
System.out.println("You Entered: " + city[i] + " with Coordinates: (" + x[i] + "," + y[i] + ") ");


}
i = i-1;
System.out.println("============================================================");

System.out.println("Calculating Distance Between: " + city[0] +", " + city[1] + ", " + city[2] + ", " + city[3] + ", " + city[4]+" >>>");
System.out.println("TOTAL of: "+ totalDistance(x, y, city, i)+ " miles.");

}


public static double totalDistance(int[] x, int[] y, String[] city, int i){

double xSub = x[i] - x[i-1];
double ySub = y[i] - y[i-1];
double distance = Math.pow(xSub, 2) + Math.pow(ySub, 2);
distance = Math.round(Math.sqrt(distance));
System.out.println("Distance From " + city[i] + " to " + city[i-1] + " is " + distance + " miles.");

if (i == 1){
return distance;
}
else {
return distance+totalDistance(x,y,city, i-1);
}
}
}

最佳答案

totalDistance(...) 函数确实是递归的(因为它调用自身)。

关于java - 被告知我的代码不是递归...寻找指导为什么不!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6405643/

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