【问题标题】:Function not breaking out on encountering return遇到返回时函数不会中断
【发布时间】:2021-06-06 23:43:40
【问题描述】:
int min_steps(int target, int move)
{
    int x,y,z;
    cout<<target<<" "<<move<<endl;
    if(target==move || target+move==0)
    {
        return 1;
    }
   
    x = 1 + min_steps(target-move,move+1);
    y = 1 + min_steps(target+move,move+1);
    z = x<y?x:y;

    return z;    
}


int main() {
    cout<<min_steps(3,1);
    return 0;
}

在上述递归函数 min_steps 中,已包含cout 语句来跟踪递归调用。现在min_steps(3,1) 遇到target=2 & move=2 的调用,在这种情况下if condition 持有True & 因此该函数应该返回1 & 中断。但这并没有发生。该函数正在继续进行调用,因此导致Time limit exceeded 错误

【问题讨论】:

  • 它确实结束了。你在期待什么?
  • target-move || target+move==0 并不代表您认为的意思。相当于写(target-move != 0) || (target+move==0)
  • target2move2 时,为什么你认为if 条件成立? 2 - 20,当转换为 bool 时是 false2 + 2 == 0 也是 falsefalse || falsefalse
  • if (target - move || target + move == 0) 等价于if (target - move != 0 || target + move == 0)。可能是一个错字,但无论如何,这看起来是个问题。
  • @Brian @Nathan Pierson 抱歉,是的,我明白你在说什么。但即使使用if(target==move || target+move==0),问题也没有终止。 (我原本打算发布这个,现在编辑问题)。

标签: c++


【解决方案1】:

问题出在这两行:

x = 1 + min_steps(target-move,move+1);
y = 1 + min_steps(target+move,move+1);

正如你所说,第一行确实返回,第二行根本没有返回。它会继续调用 (4,2) -> (5,3) -> ... 并导致 stack overflow error (0xC00000FD),除非在您的输入中已经满足 if 语句。

因此,要解决此问题,您可能需要添加更多条件或更改第二行。

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多