2011-12-31 43 views
4

我基本上是試圖改寫math.pow,我有以下明顯我沒有收到返回值的概念。我究竟做錯了什麼?用迭代法計算出的權力

public static int power(int x, int n) 
{ 
    if (n == 0) return 1; 
    int i,total; 
    for(i = 0; i < n-1 ;i++); 
    { 
     total = (x * total); 
    } 
    return total; 


} 

回答

4

需要初始化總數達到1

int total = 1; 

您只需重寫一切:在0,所以調用total = x*total將始終爲0

public static int power(int x, int n) 
{ 
    int total = 1; 
    for(int i = 0; i < n; i++) // i can be declared here directly 
    { 
     total = (x * total); 
    } 
    return total; // total remains 1 if n = 0 
} 
+0

許多正確答案爲初始化。我有一個愚蠢的做法,在我的線路之後,所以它沒有,沒有人發現這個錯誤:-)。 – orange 2011-12-31 17:13:17

+0

我在我的回答中發現並提到了,因爲我在發佈之前在日食中執行了它:) – 2011-12-31 17:20:40

+0

@Jeff:我確實瞭解到了,因爲您可以看到「;」沒有出現在我發佈的代碼中。我只是沒有想到明確提到你有一個額外的「;」。 :) – Tudor 2011-12-31 17:22:08

1

變量總開始。

需要初始化總數爲x。

3
public static int power(int x, int n) 
{ 
    int total = 1; // Initialized total to 1 
    for(int i = 0; i < n; i++) 
    { 
     total = x*total; 
    } 
    return total; 


} 
2

,而不是i < n-1你應該使用i <= n-1i < nint total=1。希望它能起作用。

還從除去; for循環結束。重寫代碼

public static int power(int x, int n){ 
     int total=1; 
     for(int i = 0;i < n;i++) 
      total *= x; 
    return total; 
} 
1

原因之一,它看起來像你的意思是:

if (n == 0) return 1; 

檢查的權力,而不是基數。

你不是初始化total要麼使用total = x會解決我認爲的事情。

0

這裏是使用日誌(n)的複雜性而不是線性的溶液。儘管如此,請注意溢出。

int pow(int x, int n) { 
    int res = 1; 
    while(n > 0) { 
     if(n % 2 == 1) { 
      res = res * x; 
     } 
     x = x * x; 
     n = n/2; 
    } 
    return res; 
}