我正在重新设计阶乘递归函数程序,以便它使用堆栈来模拟递归。我的函数似乎正在执行应有的操作,但似乎无法将“ 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,并在我的主菜单中打印出来,但这没有发生。
答案 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();
}