将递归模拟为堆栈返回错误

时间:2019-03-26 13:47:38

标签: c++

我正在重新设计阶乘递归函数程序,以便它使用堆栈来模拟递归。我的函数似乎正在执行应有的操作,但似乎无法将“ answer”的值返回给主程序。

int fact(int n)
{
    int count = n;
    int answer = 1;
    stack<int> s;
    s.push(n);
    while(count != 1)
    {
        s.push(count-1);
        count--;
    }
    while(s.top() <= n)
    {
        answer *= s.top(); //This is working
        s.pop();
    }
    cout << answer << endl; //shows no answer
    return answer; //returns nothing
}
int main()
{
    int answer = fact(5);
    cout << "answer: " << answer << endl;
    return 0;
}

我希望答案是120,并在我的主菜单中打印出来,但这没有发生。

1 个答案:

答案 0 :(得分:1)

问题在于第二个循环的终止条件

while(s.top() <= n)
{
    answer *= s.top(); //This is working
    s.pop();
}

s中没有大于n的值,因此您将在空堆栈上调用top()pop()。这是未定义的行为,充其量将是段错误。修复状况良好,可以得到预期的120:

while (!s.empty())
{
    answer *= s.top();
    s.pop();
}