所以我一直在努力弄清楚为什么这不起作用。基本上我试图编写一个递归函数,它将在控制台中显示一个漂亮的文本金字塔。
用户先输入高度,再输入用于创建金字塔的符号,这里调用函数:
//_pyramidHeight is 10
//The second int is to specify the beginning width, which should be the point at the top.
pyramidLine(_pyramidHeight, 1);
我创建的函数在这里:
void pyramidLine (int _height, int _width)
{
for (; _height > 0; _height--, _width + 2)
{
cout << setfill (' ') << setw(_height - 1);
cout << setfill (_pyramidBase) << setw(_width);
pyramidLine (_height, _width);
}
return;
}
给出的错误是这样的:Kevin_CIS121.exe 中 0x00c823e9 处未处理的异常:0xC00000FD:堆栈溢出 一旦它到达 for 循环的第一个 cout。
我现在真的不确定...
最佳答案
很简单:您永远不会遇到基本情况。你有无限递归,因为 _height--
是在你的 for
循环的每次迭代之后评估的,而不是之前。考虑 pyramidLine (_height-1, _width);
。
关于C++ - 使用递归函数创建金字塔时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9899359/