2011-06-19 56 views
2

有人向我指出,以下聲明不是遞歸。我認爲遞歸只意味着它會自己調用,直到找到答案。什麼會使這個遞歸?被告知我的代碼不是遞歸...尋找指導爲什麼不!

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); 
    } 
} 
} 

回答

7

的totalDistance(...)函數確實是遞歸的(因爲它調用本身)。

+0

+1第一個正確的答案...打我3秒! –

1

看起來像遞歸給我。誰告訴你它不是?

0

它是遞歸的。可能批評者是它太緊密迭代(循環)版本。

大概是那麼期待的是,你從中選擇了中間城市,計算了從一開始到那個城市以及從該城市到最後的距離,並添加了這個距離。距離的每一半將被計算爲調用相同的函數。

3

它是遞歸 - 它們可能意味着什麼(或者你誤解)是它不是「尾遞歸」。

這是遞歸的一個子集,它很容易優化成一個簡單的循環(儘管Java還沒有這樣做)。爲了進行尾遞歸,你必須返回遞歸調用的結果 - 在你的情況下,你首先要添加它。

相關問題