超出帕斯卡范围
procedure solve(liko_skaitmenu, rezultatas : integer);
var i, j : integer;
begin
if (not baigti) and (liko_skaitmenu = 0) and (rezultatas = b) then
begin
for j := 1 to c do
WriteLn(ats[j]);
baigti := true;
end
else
for i := 1 to N do
begin
ats[liko_skaitmenu] := i;
solve(liko_skaitmenu-1,rezultatas + a[i]);
end;
end;
所以我遇到了范围溢出错误,而且我不知道我真正超出范围的地方。我试图用这个函数做的是尝试找到 N 长度数组中等于 b 的 c 元素之和。请帮我。
procedure solve(liko_skaitmenu, rezultatas : integer);
var i, j : integer;
begin
if (not baigti) and (liko_skaitmenu = 0) and (rezultatas = b) then
begin
for j := 1 to c do
WriteLn(ats[j]);
baigti := true;
end
else
for i := 1 to N do
begin
ats[liko_skaitmenu] := i;
solve(liko_skaitmenu-1,rezultatas + a[i]);
end;
end;
So I'm getting range overrun error, and I don't see where I really got out of range. What I'm trying to do with this function is try to find sum of c elements in N length array that equals b. Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 liko_skatimenu 为 0 时,有可能计算结果为 false,因为计算结果也取决于 rezultatas 和 baigti。如果下次继续,您将得到
ats[-1] := i;
,这可能不是您想要的。我会把它改成这样:There's the possibility that this evaluates to false when liko_skatimenu is 0, because the result of the evaluation depends on rezultatas and baigti too. If it proceeds next time you'll have
ats[-1] := i;
, which probably isn't what you wanted. I'd change it into something like:这些代码使用了几个全局变量,这使得理解变得困难,并且您没有显示在调用过程之前如何初始化变量。如果代码示例是英文的也会有帮助。
无论如何,
rezultatas > 的可能性。 b.
。if
上的复杂条件,ats[liko_skaitmenu] := i;
可能会以liko_skaitmenu
liko_skaitmenu
的值执行。 1.
.您可能想要更多类似的东西:
也就是说,该方法是 O(N^c)。您可以通过对数组进行排序并将递归步骤限制为数组中可以保存答案的部分来做得更好,或者您可以使用数组中 c 个数字的组合。有 许多类似的问题在这个论坛上都有很好的答案。
The codes uses several global variables that make it difficult to understand, and you don't show how the variables are initialized before the procedure is called. It would also help if the code sample was in English.
Any way,
rezultatas > b
.if
, theats[liko_skaitmenu] := i;
may be executed with values ofliko_skaitmenu < 1
.You probably want something more like:
That said, the approach is O(N^c). You can do better than that by sorting the array and restricting the recursive step to parts of the array that can hold the answer, or you can work with the combinations of c numbers in the array. There are many alike questions with good answers in this forum.