以下の文は再帰ではないことが私に指摘されました。再帰とは、答えが見つかるまで自分自身を呼び出すということです。この再帰は何をするでしょうか?私が持っているコードは再帰ではないと言われました...なぜガイダンスを探していないのですか?
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);
}
}
}
+1の最初の正解... 3秒で私を打つ! –