如何将简单循环转换为使用递归?
所以我有这样的代码:
WRITELN( “input which member of series”)
READ(n)
p ← 2
prev1 ← 1
prev2 ← 1
WHILE p IS LESS THAN n DO
BEGIN
term ← prev1 + prev2
prev2 ← prev1
prev1 ← term
p ← p + 1
END
WRITELN (“term =”, term)
有人可以帮我重写代码,使其递归地工作(在 PHP 或 Pascal 中)。
编辑
N = 4
我正在使用帕斯卡。问题是,非递归代码返回 3,而递归代码返回 2。
这是我的递归代码:
program Fibfun;
VAR
n,prev1,prev2,term : Integer;
FUNCTION sw(p:integer):integer;Begin
if p < n then
Begin
term:= prev1 + prev2;
prev2:=prev1;
prev1:=term;
End
else
Begin
p:= 1 + sw(p);
End;
sw:=term;
End;
Begin
prev1:=1;
prev2:=1;
term:=1;
writeln('Input number: ');
readln(n);
writeln('term ', sw(2));
readln;
End.
So I have this code:
WRITELN( “input which member of series”)
READ(n)
p ← 2
prev1 ← 1
prev2 ← 1
WHILE p IS LESS THAN n DO
BEGIN
term ← prev1 + prev2
prev2 ← prev1
prev1 ← term
p ← p + 1
END
WRITELN (“term =”, term)
Can someone help me rewrite the code so it works recursively (in either PHP or Pascal).
EDIT
N = 4
I'm using PASCAL. The problem is, the non-recursive code returns 3, while the recursive code returns 2.
This is my recursion code:
program Fibfun;
VAR
n,prev1,prev2,term : Integer;
FUNCTION sw(p:integer):integer;Begin
if p < n then
Begin
term:= prev1 + prev2;
prev2:=prev1;
prev1:=term;
End
else
Begin
p:= 1 + sw(p);
End;
sw:=term;
End;
Begin
prev1:=1;
prev2:=1;
term:=1;
writeln('Input number: ');
readln(n);
writeln('term ', sw(2));
readln;
End.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)