[英]How can I exit from a recursive function?
我正在研究一个使用递归函数的程序。
我的问题是当递归函数的工作完成,并且控制转移到下一个函数时,它在完成下一个函数的工作后返回到递归函数。
我需要一些可以强制控制权转移回功能的代码。 我不想退出我的程序。
public void function1(a, num)
{
if(a >= num)
{
if(a > num)
function1(a, num);
else if(a == num)
{
a++;
function1(a, num)
}
}
else
function2(a, num)
}
public void function2(a, num)
{
//print result;
}
每次我调用function1
,我都会对变量a
和num
进行一些更改。 但问题是在某些情况下,当function2
时,控制再次传递给function1
。 你可以提供一些代码来防止这种情况吗? 它是我正在设计的时间表生成器的一部分。
把一回 ,每当你想返回基地
此版本的功能完全相同。
public void function1(a, num)
{
if (a < num)
{
function2(a, num);
}
else
{
function1((a > num) ? a : a + 1, num);
}
}
public void function2(a, num)
{
//print result;
}
只是为了你的信息:如果a
传递,大于num
,那么函数将无限递归,同时参数列表function1(a, num)
有效调用,因此它永远不会返回导致挂断并最终堆栈在某些时候溢出。
您需要将其更改为:
public void function1(a,num)
{
if(a>num)
{
//Increment num or decrease a here, otherwise the recursion never ends
function1(a,num);
return; //Each time the method does a recursion, it stops to execute itself with
// a new set of arguments, but when one of them decide it's over, all the
// instances of the method will resume one by one, so if you don't return,
// it executes the rest of function1.
}
else if(a==num)
{
a++; //You probably don't want to do that, this a==num case should be merged
// with a>num. Can you see why?
function1(a,num)
return;
}
else
function2(a,num)
}
public void function2(a,num)
{
//print result;
}
如果您只执行一个直接循环,代码可能会更简单。
while (a <= num)
{
function2(a, num);
a++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.