[英]Why does my recursive function in C cause a stack overflow?
I'm trying to make a function calculating x to the power n (where x could be a double, n must be an int
). 我正在尝试计算x到幂n的函数(其中x可以是double,n必须是
int
)。 A recursive algorithm would be this one , but implementing it in C gave me the stack-overflow error. 递归算法就是这个算法,但在C中实现它会给出堆栈溢出错误。
I tried finding my answer here, but the closest I found was this , which didn't satisfy my needs. 我试着在这里找到答案,但我找到的最接近的是这个 ,这不符合我的需要。
Here is my code: 这是我的代码:
double power_adapted(double x, int n) {
if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}
The recursive calls always pass 2 as n, so they will always trigger another recursive call. 递归调用总是将2作为n传递,因此它们将始终触发另一个递归调用。
I think you misinterpreted the formula. 我想你误解了这个公式。 I would interpret it as:
我会把它解释为:
else if (n % 2 == 0) {
double v = power_adapted(x, n / 2);
return v * v;
}
else {
double v = power_adapted(x, (n - 1) / 2);
return x * (v * v);
}
I don't think what you're trying to accomplish makes sense. 我不认为你想要完成的事情是有道理的。
If you take a look at this part of code, 如果你看看这部分代码,
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return power_adapted(power_adapted(x, (n - 1) / 2), 2);
While the nested calls may present no problem (as a statement), the call on the outside always has n = 2
and the base cases depend on n
. 虽然嵌套调用可能没有问题(作为语句),但外部调用总是
n = 2
,基本情况依赖于n
。
By taking a look at the formula provided, I think you should have a base case for n == 2
to return x * x
(this is the simplest change to the algorithm). 通过查看提供的公式,我认为你应该有一个
n == 2
的基本情况来返回x * x
(这是对算法的最简单的改变)。 So, the algorithm could be stated as follows: 因此,算法可以表述如下:
double power_adapted(double x, int n) {
if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n == 2)
return x * x;
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.