我基本上是在尝试重写 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;
}
最佳答案
你需要将total初始化为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
}
关于java - 使用迭代计算幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689343/