【发布时间】:2016-03-01 14:55:46
【问题描述】:
我收到了
“System.StackOverflowException”类型的未处理异常 发生在 mscorlib.dll'中
运行以下代码时出错。我无法弄清楚我哪里出了问题以及如何纠正它。有人可以帮我解决这个问题吗?
代码应该通过整数列表进行过滤,给定整数的哪组匹配目标数字;整数组被放入一个列表中,然后该列表被放入另一个列表中,以便进程继续处理剩余的数字。
我们将不胜感激任何和所有帮助。谢谢
List<List<int>> results = null;
public void Listing(List<int> numbers)
{
int target = Convert.ToInt32(textBox15.Text);
Solver solver = new Solver();
results = solver.Solve(target, numbers.ToArray());
}
public class Solver
{
private List<List<int>> mResults;
int t = 0;
public List<List<int>> Solve(int goal, int[] elements)
{
int t = goal;
mResults = new List<List<int>>();
RecursiveSolve(goal, 0, new List<int>(), new List<int>(elements), 0);
return mResults;
}
private void RecursiveSolve(int goal, int currentSum, List<int> included, List<int> notIncluded, int startIndex)
{
List<int> nextIncluded = new List<int>(included);
List<int> nextNotIncluded = new List<int>(notIncluded);
try
{
for (int index = startIndex; index < notIncluded.Count; index++)
{
int nextValue = notIncluded[index];
if (currentSum + nextValue == t)
{
List<int> newResult = new List<int>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
t = goal;
}
else if (currentSum + nextValue < t)
{
nextIncluded.Add(nextValue);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(t, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++);
}
else if (currentSum + nextValue > t)
{
nextNotIncluded.Remove(nextValue);
nextNotIncluded.Add(nextValue);
t = t - 50;
RecursiveSolve(t, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error Message : " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
【问题讨论】:
-
数学问题的提示:在 Visual Studio 中右键单击项目 -> 选择“属性”。在“属性”中选择“构建”,然后在最底部单击“高级”。在“高级”窗口中检查/标记“检查算术上溢/下溢”,保存然后尝试再次运行您的应用程序
-
我不完全理解发生了什么,但请查看您的第三个
else块:这是正确的:nextNotIncluded.Remove(nextValue); nextNotIncluded.Add(nextValue);?好像有什么不对劲。猜第一行应该是nextIncluded.Remove(nextValue)而不是nextNotIncluded... -
感谢 Jasper,不幸的是,这一次并没有起到什么作用;我仍然收到错误消息。
-
Rene - 这是正确的,我希望将下一个值移动到列表的末尾,这样虽然这次不符合要求,但以后仍然可以使用。
-
在 Visual Studio 2013 中单击顶部的“调试”,然后单击菜单中的“异常”。在“例外”窗口中单击“查找”并在列表中搜索 SO,然后选中/标记并再次运行
标签: c# integer unhandled-exception mscorlib