c++ - 在C++中的递归函数中返回

标签 c++ recursion

我在这里有点困惑。让我们看下面的代码:

bool testing(int i) {

    if((i%2)==0) {
        return true;
    } else {
        --i;
        testing(i);
    }
    return false;
}

当我执行testing(5)时,我期望该函数返回true,因为在某个时候,5将变为4,因此成为4 % 2 == 0,因此该函数将返回true,但事实并非如此。怎么了?

最佳答案

递归的想法是当函数直接或间接调用时。
如果将代码中的函数修改为:

bool testing(int i){
    // test if even, if so return true
    if((i % 2) == 0){
        return true;
    // otherwise decrement and test again
    }else{
        // at this point the function calls itself with decremented argument
        return testing(--i);
    }
    // I doubt that this case will be ever returned  
    // more likely your function will return "true" or run "forever" decrementing
    return false;
}

为了避免无限循环,您需要一个基本情况,即终止条件,该条件可产生结果而无需递归。例如,如果i变得非常小或为负数,则返回false
bool testing(int i){
    // base case
    if(i < 0) return false;
    // rest of the function
    if((i % 2) == 0){
        return true;
    }else{
        return testing(--i);
    } 
}

更简洁一点,您最终有以下三种情况:
bool testing(int i){
    // base case
    if(i < 0) return false;
    // test if even
    if((i % 2) == 0) return true;
    // recursion step
    return testing(--i);
}

如需进一步阅读,请检查this

关于c++ - 在C++中的递归函数中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215194/

相关文章:

c++ - mktime 仅处理 Clang 上的闰年?

c++ - 使用 Qt Creator 交叉编译 Qt 应用程序的简便方法?

c++ - 错误:'std::cout 中的 'operator<<"不匹配

c++ - 将基于递归 DFS 的拓扑排序转化为非递归算法(不丢失循环检测)

c++ - 如何创建可变参数泛型 lambda?

c++ - 将弱符号和局部符号链接(symbolic link)在一起时,可能的GCC链接器错误导致错误

c - 递归函数的增长顺序

javascript - AngularJS 递归 ng-repeat 变量与 ng-include 绑定(bind)

algorithm - 仅使用归纳法求解递归 T(n)=t(n/2)+sqrt(n)

java - 在java中使用递归反转整数列表数组