读书人

递归为什么报 stackOverflow解决思路

发布时间: 2012-04-12 15:46:35 作者: rapoo

递归为什么报 stackOverflow

C/C++ code
// 0304.cpp : Defines the entry point for the console application.//#include "stdafx.h"int printResult(int n){     int temp = printResult(n);   if(n == 0)    {        printf("n ===== %d \t result = %d\n", n, temp);  //here.......      return 1;   }     return printResult(n -1)*n;}int _tmain(int argc, _TCHAR* argv[]){       printResult(10);    return 0;}


[解决办法]
int printResult(int n)
{
int temp = printResult(n); //一直递归啊。。肯定栈溢出。。。
if(n == 0)
{
printf("n ===== %d \t result = %d\n", n, temp); //here.......
return 1;
}
return printResult(n -1)*n;
}
=》
int printResult(int n)
{
if(n == 1)
{
return 1;
}
return printResult(n -1)*n;
}

main()
{
printf(printResult(n))
}
[解决办法]
因为你的递归函数没有出口,在函数的第一句: int temp = printResult(n);就将继续递归,而且参数值不变,这样就是无止境的递归下去,直到你的栈溢出。
[解决办法]
没看懂你的递归函数是干什么的

堆栈溢出了,无限递归了

int temp = printResult(n);
一直执行这句。

读书人网 >C语言

热点推荐