2015-10-25 70 views
1
public class collatzpow { 

    public static int collatz(int n) { 

     StdOut.print(n + " "); 
     if (n == 1) return 0; 
     if (n% 2 == 0) return collatz(n/2); 
     else return collatz(3*n + 1); 

    } 

    public static void main(String[] args) { 

     int n= Integer.parseInt(args[0]); 
      StdOut.println(collatz(7)); 
    } 
} 

我想設置一個全局變量來計算程序調用遞歸的次數。我知道數字7它叫它17次。設置一個全局變量來計算遞歸

我被告知這很容易,但我正在努力一點。

+0

不確定StdOut是什麼。在java中,你通常使用System.out。爲了擁有這樣一個全局變量,只需在你的類中聲明它,比如'class Whatever {static int recursionCounter = 0; ...'然後你可以從你的方法中增加和打印這個變量。 – GhostCat

回答

0

只需在類作用域中聲明一個靜態int變量,並在每次調用該方法時增加。

public class collatzpow { 

public static int count = 0; 
public static PrintStream StdOut = System.out; 

public static int collatz(int n) { 
    ++count; 
    StdOut.print(n + " "); 
    if (n == 1) return 0; 
    if (n % 2 == 0) return collatz(n/2); 
    else return collatz(3 * n + 1); 

} 

public static void main(String[] args) { 

    int n = Integer.parseInt(args[0]); 
    StdOut.println(collatz(7)); 
    System.out.println(count); 
} 
    }