c++ - 为什么我的 C++ 递归程序永远运行

标签 c++ recursion stack-overflow

我正在编写一个倒金字塔控制台应用程序,当您输入一个数字时,例如 3,它会输出它和楼梯的数量,

*****
 ***
  *

它可以工作,一切都很好,但是当它输出金字塔时。它会一直发送垃圾邮件空间,直到程序崩溃。这是源代码: 注意:这是一个递归项目。

#include <iostream>
using namespace std;

int Pyramid(int n, int index)
{
    if(index > n)  //Base Case
    {
        return 0;
    }
    for(int i=index+1; i<=n; i++)
    {
        cout<<" ";
    }
    for(int j=1; j<index*2; j++)
    {
        cout<<"*";
    }
    cout<<endl;
    return Pyramid(n, index-1);
}

int main()
{
    int n;
    cin>>n;
    Pyramid(n, n);
    return 0;
}

谁能帮我解决这个问题并让它成为一个递归项目?

最佳答案

你递归的停止条件是错误的。 这是我所做的,它正确显示了星形金字塔

int Pyramid(int n, int index)
{
    // your stop condition is wrong (not index>n but index ==0)
    if (index ==0 )
    {
        return 0;
    }
    //until here
    for(int i=index+1; i<=n; i++)
    {
        cout<<" ";
    }
    for(int j=1; j<index*2; j++)
    {
        cout<<"*";
    }
    cout<<endl;
    return Pyramid(n, index-1);
}

示例执行如下:

10
*******************
 *****************
  ***************
   *************
    ***********
     *********
      *******
       *****
        ***
         *

关于c++ - 为什么我的 C++ 递归程序永远运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66901673/

相关文章:

c++ - 如何从 C++ 代码打开一个新终端并在其中写入

c++ - 如何使用 boost::hash 获取文件内容哈希?

sql - 递归SQL查询·

memory - Haskell 堆栈溢出

C++ - 常量变量,这是一个正确的术语吗?

c++ - Juce vst 合成器 : cannot instantiate abstract class

python - 递归调用复杂度

javascript - 是否可以非递归地编写这个函数并且没有多余的行?

c++ - 在 C++ 中增加堆栈大小

c - 这会导致堆栈出现问题吗?