有人向我指出,下面的陈述不是递归。我认为递归只意味着它会调用自己直到找到答案。什么会导致这种递归?
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);
}
}
}
答案 0 :(得分:7)
totalDistance(...)函数确实是递归的(因为它自己调用)。
答案 1 :(得分:3)
它是递归 - 它们可能意味着什么(或者你误解了)是它不是“尾递归”。
这是递归的一个子集,非常简单,可以优化为一个简单的循环(尽管Java还没有这样做)。要进行尾递归,您必须返回递归调用的结果 - 在您的情况下,首先添加它。
答案 2 :(得分:1)
看起来像是递归给我。谁告诉你这不是?
答案 3 :(得分:0)
它是递归的。可能批评者认为迭代(循环)版本过于紧密。
可能然后期待,不是从头到尾经过列表,而是选择中间城市,计算从开始到该城市以及从该城市到结束的距离并添加。将计算距离的每一半,调用相同的函数。