2012-11-01 13 views
2
public static int exponent(int baseNum) { 
    int temp = baseNum *= baseNum;     

     return temp * exponent(baseNum);    
} 

現在上面的方法做N * N爲無窮大,如果我調試它,所以它仍然有效,但我需要這個遞歸方法,因爲我的教練要求我們必須找到給出的指數10倍後停止10.遞推指數的方法

電源的方法必須只有一個參數,這裏的調用指數的一些例子:

   System.out.println ("The power of 10 in " + n + " is " + 
        exponent(n)); 

所以輸出應該是:

The power of 10 in 2 is 1024 

OR

The power of 10 in 5 is 9765625 
+0

你的遞歸方法沒有基本的情況! –

+0

如果您需要在十次後停止,則需要爲其遞歸次數設置一個變量。 –

+0

你需要將權力作爲參數傳遞,比如'power(baseName,n);'每次遞歸時減少1。 –

回答

0

創建一個輔助方法做遞歸。它應該有兩個參數:基數和指數。爲指數調用它的值爲10,並用(指數-1)進行遞歸。基本情況是exponent == 0,在這種情況下它應該返回1.(您也可以使用exponent == 1作爲基本情況,在這種情況下它應該返回基數。)

0

不應該有2個參數並處理退出條件像下面一樣?

public static int exponent(int baseNum, int power) { 
    if(power == 0){ 
     return 1; 
    }else{ 
     return baseNum * exponent(baseNum, power-1); 
    }   
} 
3

這樣做

public static int exp(int pow, int num) { 
    if (pow < 1) 
     return 1; 
    else 
     return num * exp(pow-1, num) ; 
} 

public static void main (String [] args) {  
    System.out.println (exp (10, 5)); 
} 

,不要忘記的基本情況(即條件)告訴何時停止遞歸和從棧中彈出的值。

0

遞歸函數,我們需要:

  1. 檢查停止條件時(即exp爲0,返回1)
  2. 調用本身具有調整的條件(即基礎*基地^(N-1) )

這是代碼。

public class Test 
{ 
    public static int exponent(int baseNum, int exp) 
    { 
     if (exp<=0) 
      return 1; 

     return baseNum * exponent(baseNum, --exp); 
    } 

    public static void main(String a[]) 
    { 
     int base=2; 
     int exp =10; 

     System.out.println("The power of "+exp+" in "+base+" is "+exponent(base,exp)); 
    } 

} 
0

不要忘記,對於每個遞歸函數,您都需要一個基本情況。一個停止condition` 靜態雙R2(浮動基地,INT N) {

if (n<=0) return 1; 
    return base*r2(base,n-1); 

} 
1

以下是我的導師,賓夕法尼亞武教授在他的演講說明中提供。

 
public class Exp
{
public static int exponent(int a, int n)
{
if (n==0) { return 1; } // base
else // recursion
{
a *= exponent(a, n-1);
return a;
}
}
public static void main(String[] args)
{
System.out.print(exponent(2, 10));
}
}