c - 为什么这个程序只运行一次?

标签 c recursion

所以我试图通过递归函数将数字提高到一定的幂。我的代码对我来说似乎是正确的,但它的行为很奇怪,因为它只运行一次。我似乎无法理解为什么。

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/

相关文章:

c - X11透明窗口: click-through only where alpha = 0

c - C语言中位域的实际用途是什么?

c - c 中未处理的异常

java - 如何知道我的代码的哪一部分占用更多 CPU

PHP 将变量传递给 array_walk_recursive

c - 24bpp 到 8bpp 转换 C 与原始图像数据

c++ - 可以查询 OpenAL 设备它喜欢的频率和格式吗?

Powershell:在特定创建时间范围内递归搜索驱动器或目录中的文件类型

algorithm - Scala 中的合并排序

python - 当前导数字为零时,在 python 中添加数字的递归函数失败