所以我试图通过递归函数将数字提高到一定的幂。我的代码对我来说似乎是正确的,但它的行为很奇怪,因为它只运行一次。我似乎无法理解为什么。
double to_pow(int zahl, int potenz){
zahl+=zahl;
potenz-=1;
if(potenz!=0){
to_pow(zahl, potenz);
}
return zahl;
}
int main(){
double res = to_pow(9,3);
printf("%.lf", res);
}
最佳答案
让我尝试解决这个问题:
Why does my recursive algorithm appear to run only once?
递归实际上完成了,但对输出值没有影响。递归计算的结果将被忽略。
下面是一些注释,可以使这一点更清楚:
double to_pow(int zahl, int potenz){
// we double the first input value and decrease the second input value
zahl+=zahl;
potenz-=1;
if(potenz!=0){
// depending on some criterion we call the function recursively
// but the function has no side-effects and the return value is not used
to_pow(zahl, potenz);
}
// we return the doubled input value
return zahl;
}
要解决此问题,您应该使用递归函数调用的返回值来实际计算算法的最终输出。
一旦有了这个,您应该解决实现中的其他问题,即它实际上做了它应该做的事情。
关于c - 为什么这个程序只运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59193451/