递归函数中的分段错误C++

use*_*514 3 c++ recursion segmentation-fault

为什么我的递归函数会出现分段错误.每当我将一个大于4的值作为参数调用它时,就会发生这种情况

#include <iostream>
#include <limits>

using namespace std;    

int printSeries(int n){
    if(n==1){       
        return 1;
    }
    else if( n==2){     
        return 2;
    }
    else if( n==3){
        return 3;
    }
    else if( n==4){
        return printSeries(1) + printSeries(2) + printSeries(3);
    }
    else{       
        return printSeries(n-3) + printSeries((n-2) + printSeries(n-1));
    }
}


int main(){

        //double infinity = numeric_limits<double>::max();

        for(int i=1; i<=10; i++){
            cout << printSeries(i) << endl;
        }

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我不确定是否返回正确的结果:

return printSeries(n-3) + printSeries(n-2) + printSeries(n-1);
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 18

return printSeries(n-3) + printSeries( (n-2) + printSeries(n-1) );
//                                     ^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

括号的不正确嵌套会导致无限递归,从而导致堆栈溢出(segfault).

n = 4 时考虑,

f(4) = 1 + f(2 + f(3))
     = 1 + f(2 + 3)
     = 1 + f(5)
     = 1 + [ f(2) + f(3 + f(4)) ]
     = ...
Run Code Online (Sandbox Code Playgroud)

  • @the_drow:为什么?它完全有效,它只会导致无限递归. (2认同)
  • @the_drow:不幸的是,C++中没有`std :: programmer_error`.不过,你可能想提出它. (2认同)