如何在这里处理堆栈溢出异常 [英] how to handle the stack overflow exception here
本文介绍了如何在这里处理堆栈溢出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class program5 //----STACK OVERFLOW EXCEPTION
{
public int sum(int n)
{
int s;
s = n + sum(n-1);
return s ;
}
static void Main(string[] args)
{
program5 p = new program5();
p.sum(5);
}
}
推荐答案
肯定是一项功课!
这是一种递归方法,可能正在对自然数求和.以下应该没问题:
Surely a homework!
It''s a recursive method that probably is doing sum of natural numbers. Following should be ok:
public int sum(int n)
{
if(n==1)
return 1;
int s;
s = n + sum(n-1);
return s ;
}
最常见的堆栈溢出原因是深度过大或无限递归,因此您需要以某种条件终止.
The most common cause of stack overflow is excessively deep or infinite recursion.So you need to terminate with some condition.
这篇关于如何在这里处理堆栈溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文