我基本上是试图改写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;
}
我基本上是试图改写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;
}
需要初始化总数达到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
}
变量总开始。
需要初始化总数为x。
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;
}
,而不是i < n-1
你应该使用i <= n-1
或i < n
和int 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;
}
原因之一,它看起来像你的意思是:
if (n == 0) return 1;
检查的权力,而不是基数。
你不是初始化total
要么使用total = x
会解决我认为的事情。
这里是使用日志(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;
}
许多正确答案为初始化。我有一个愚蠢的做法,在我的线路之后,所以它没有,没有人发现这个错误:-)。 – orange 2011-12-31 17:13:17
我在我的回答中发现并提到了,因为我在发布之前在日食中执行了它:) – 2011-12-31 17:20:40
@Jeff:我确实了解到了,因为您可以看到“;”没有出现在我发布的代码中。我只是没有想到明确提到你有一个额外的“;”。 :) – Tudor 2011-12-31 17:22:08