【问题标题】:Returns in Recursive Function in C++在 C++ 中的递归函数中返回
【发布时间】:2023-03-14 09:48:02
【问题描述】:

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

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,但它只是' t 的情况。怎么了?

【问题讨论】:

  • 你在调试器中单步执行了吗?然后你可以看到发生了什么
  • 我认为你应该有return testing(i)。它的方式调用testing(),但它继续并返回false。
  • 作为优化说明,您最好使用if((i&1)==0) 而不是if((i%2)==0)。最好还是使用return testing(i-1) 而不是--i ; return resting(i),尽管优化器无论如何都会优化那个。
  • @iAdjunct。谢谢你的建议。
  • @iAdjunct i&1i%2 不等同于负数。

标签: c++ recursion


【解决方案1】:

您应该return testing(i); 而不仅仅是testing(i);

【讨论】:

  • 是的,它无法访问。这是一个单独的问题。
【解决方案2】:

递归的概念是一个函数直接或间接调用自身
如果将代码中的函数修改为:

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

【讨论】:

  • 优化是指删除大括号?你也不需要最后一个else
  • @Emz 你是对的,代码写得更清晰简洁,没有优化,else 确实是不需要的。谢谢:)
  • 我建议阅读stackoverflow.com/questions/8020228/…这个问题。
  • @Emz(个人意见)花括号如果在流控制语句之后可以放在同一行,可以省略花括号 /i>。在“书籍”中有一些示例省略了 花括号 并在下一行“python 样式”中使用了 indentation,但这确实是模棱两可的。如果有较大的代码块,则应将其括起来。
【解决方案3】:

你不会冒泡最终的返回值;您需要在递归调用中使用 return 。此外,您可以简化预减量:

return testing(--i);

【讨论】:

    【解决方案4】:

    因为你只调用testing(i) 函数。这就是为什么它不是递归调用的原因。

    你应该写return testing(i)

    【讨论】:

      【解决方案5】:

      它返回false,因为它的返回值被最后一条“return false”语句覆盖。

      【讨论】:

        猜你喜欢
        • 2018-07-15
        • 2022-07-21
        • 2017-10-29
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 2017-03-24
        • 1970-01-01
        相关资源
        最近更新 更多