【问题标题】:G++ Compiler won't allow recursion?G++ 编译器不允许递归?
【发布时间】:2010-10-13 18:04:51
【问题描述】:

我创建了一个使用递归的非常简单的程序。我正在使用 g++ 编译器。我可以编译它,但是当我尝试运行它时,我收到一条错误消息,上面写着 SEGMENTATION FAULT。这是我的代码:

#include <iostream.h>
using namespace std;

int Recurse(int);

int main(int argc, char *argv[])
{
        Recurse(10);
        cout << endl;
}

int Recurse(int numTimes)
{
    if (numTimes == 0)
        return 0;
    else
        {
                cout << numTimes << " ";
        Recurse(numTimes--);
        }
}

【问题讨论】:

    标签: c++ recursion


    【解决方案1】:

    在递归调用中,您使用的是后缀 -- (numTimes--),而不是前缀版本 (--numTimes)。结果,numTimes 的值在递归调用之后递减。这意味着 Recurse 被无限调用 10。使用前缀版本(调用前会递减),或者直接传递numTimes-1(因为不需要修改numTimes值)。

    您看到段错误的原因是您的堆栈溢出到受保护的内存中。

    【讨论】:

    • +1 表示堆栈溢出并建议使用 x-1 而不是 x--。
    【解决方案2】:

    可能是“numTimes--”导致了无限递归。后缀 -- 将减少 -- 方法中的值,但将返回变量的原始值。

    尝试将其更改为 --numTimes。

    【讨论】:

      【解决方案3】:

      在将 numTimes 传递给 Recurse() 之后,您将递增 numTimes,因此您通过连续递归到 Recurse 值为 10 并且从不向 cout 输出任何内容来破坏堆栈。

      【讨论】:

      • 嘿,stackoverflow 上的堆栈溢出 :)
      【解决方案4】:

      首先,你要使用

      #include <iostream>
      

      没有.h

      现在是程序:

      #include <iostream>
      using namespace std;
      
      int Recurse(int);
      
      int main(int argc, char *argv[]) {
              Recurse(10);
              cout << endl;
      }
      
      int Recurse(int numTimes) {
          if (numTimes == 0)
              return 0;
          else {
              cout << numTimes << " ";
              return Recurse(--numTimes);
          }
      }
      

      您需要在评估之前应用 - 1。

      【讨论】:

        猜你喜欢
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 2019-04-21
        相关资源
        最近更新 更多