使用迭代计算幂次方

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;


}
6个回答

4

您需要将总数初始化为1。

int total = 1;

您可以把所有内容重写为:

您可以将所有内容重写为:

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   
}

初始化有很多正确的答案。我也做了一些愚蠢的事情,在我的for语句后面加了一个分号,所以它没有执行,没有人发现那个错误 :-). - orange
我在回答中提到并找到了它,因为在发布之前我在我的Eclipse中执行了它 :) - dku.rajkumar
@Jeff:我确实注意到了,正如你所看到的,在我发布的代码中没有出现“;”。我只是没有想到明确提到你多了一个“;”。 :) - Tudor
@dku.rajkumar 抱歉!我没有仔细阅读。(这是我的问题 :-()。) - orange

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-1i < n以及int total=1,而不是i < n-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

变量total开始为0。所以调用total = x * total将始终为0。

您需要将total初始化为x。


1

首先,看起来你的意思是:

if (n == 0) return 1;

检查能力,而不是基数。

您也没有初始化total,使用total = x应该可以解决问题。


0

这里有一个log(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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接