帮我看看pascal的问题

来源:百度知道 编辑:UC知道 时间:2024/05/03 12:07:26
题目:自然数1~N从左到右排列,在相邻两个数之间添加一个“+”或“-”,使所得式子的代数和等于自然数K。
程序:
{program daishuhe(input,output);}
var n,k,i,j,s,l:integer;
chuan:string;
procedure try(l:longint);
var g,h:integer;
xchuan:string;
begin
if (l=n) and (s=k) then writeln(chuan)
else
begin
str(l,xchuan);
g:=length(chuan);
chuan:=chuan+'+'+xchuan;
h:=length(chuan)-g+1;
s:=s+l;
try(l+1);
delete(chuan,g+1,h);
chuan:=chuan+'-'+xchuan;
s:=s-2*l;
try(l+1);
end;
end;
begin
{assign(input,'word.in');
reset(input);
assign(output,'word.out');
rewrite(output);}
readln(n,k);
chuan:='1';
s:=1;
try(2);
end.
我用watches看,一运行到try(2)就会202错误,为什么?
即使解决202还有问题。

堆栈溢出
你的过程里没有结束条件,导致不断递归下去
可以加一句
if i=n+1 then exit;

你把思路说一下,
我记得这要用动态规划的,不知道你怎么so easy
穷举?
不过我当年做的有点不同
是要与k的差的绝对值最小。

调试时,不用f8,用f7或f4试试

202错误是因为堆栈溢出
查查是不是因为过程没有正确返回