【问题标题】:Why my C++ Recursion Program keeps on forever为什么我的 C++ 递归程序永远存在
【发布时间】:2021-06-28 06:49:00
【问题描述】:

我正在编写一个倒金字塔控制台应用程序,当你输入一个数字时,例如 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;
}

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

【问题讨论】:

  • 一些旁注:(1) Don't use using namespace std (2) 正确缩进和格式化你的代码,或者使用clang-format。跨度>
  • @asynts 我没有使用任何其他头文件,所以不需要删除using namespace std,为了格式化,我下次格式化我的代码,谢谢。

标签: c++ recursion stack-overflow


【解决方案1】:

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

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
*******************
 *****************
  ***************
   *************
    ***********
     *********
      *******
       *****
        ***
         *

【讨论】:

  • 谢谢
【解决方案2】:

    if(index > n)  //Base Case
    {
        return 0;
    }

这似乎不正确。您以n 开始索引,并且索引将始终递减。 index &gt; n 永远无法联系到。

【讨论】:

  • 这也有帮助,在此先感谢
猜你喜欢
  • 1970-01-01
  • 2011-05-26
  • 2015-03-13
  • 1970-01-01
  • 2011-10-28
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多