在运行代码时收到堆栈溢出异常,多次递归调用
本文关键字:异常 调用 递归 栈溢出 堆栈 代码 运行 | 更新日期: 2023-09-27 17:52:11
我认为这些特定的代码行是错误的原因。
有什么办法可以解决这个问题吗?Z保存grid类型对象的静态int变量的值。对于这个代码,有一个随机大小的网格。在代码的开头,单个网格点"移动"到另外两个网格点,然后每个网格点"移动"到另外两个网格点,以此类推。
递归应该在有3000次遍历时停止。每次"行走"一个网格点时,行走的次数也会更新。因此,行走次数是坐标类的静态变量,坐标类是构成每个网格点的对象类型。
坐标就是x和y的分量。"int a"answers"int b"是在Recurs方法中分别接受"x"answers"y"网格组件的参数。x和y分量在递归walk方法中是随机分配的。
//Walks
public void Recurs(int a, int b)
{
grid[a, b].updateAccessed();
grid[a, b].setWalkCount();
int z = grid[a, b].getWalkCount();
if (z == 3000)
{
return;
}
else
{
int one = rand.Next(20);
int two = rand.Next(20);
//int three = rand.Next(20);
int four = rand.Next(25);
int five = rand.Next(25);
//int six = rand.Next(25);
Recurs(one, four);
Recurs(two, five);
//Recurs(three, six);
}
}
//Walks to any grid point recursively
public void RecursiveWalk()
{
int x = rand.Next(20);
int y = rand.Next(25);
Recurs(x, y);
}
你在每个递归中调用两次递归吗?你能改变你的状况吗?
//Walks
public void Recurs(int a, int b)
{
grid[a, b].updateAccessed();
grid[a, b].setWalkCount();
int z = grid[a, b].getWalkCount();
//i assume in 1 of your recursion,
//the count was set to 3001 and it continues
if (z >= 3000) //<-- >= instead of =
{
return;
}
else
{
int one = rand.Next(20);
int two = rand.Next(20);
//int three = rand.Next(20);
int four = rand.Next(25);
int five = rand.Next(25);
//int six = rand.Next(25);
Recurs(one, four);
Recurs(two, five);
//Recurs(three, six);
}
}
//Walks to any grid point recursively
public void RecursiveWalk()
{
int x = rand.Next(20);
int y = rand.Next(25);
Recurs(x, y);
}
我根本看不出使用递归的理由。你能像这样简单地使用一个循环吗?
public void IterativeWalk()
{
for (int z=0; z<3000; z++)
{
int x = rand.Next(20);
int y = rand.Next(25);
grid[x, y].updateAccessed();
grid[x, y].setWalkCount();
}
}