如何将简单循环转换为使用递归?

时间:2011-08-02 07:30:21

标签: loops recursion pascal

所以我有这段代码:

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

我正在使用PASCAL。问题是,非递归代码返回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.

1 个答案:

答案 0 :(得分:0)

program test;     
var
 result : longint;
 num,i, error: integer;
 strnum: string;

function fib(n : integer) : longint;
begin
    if n <= 2 then fib := 1
    else fib := fib(n-2) + fib(n-1);
end;

begin
if ParamCount = 0 then
begin
  writeln('Enter integer:');
  readln(strnum);
  val(strnum,num,error);
end else 
begin
 val (ParamStr(1), num, error);
end;
for i := 1 to num do
begin
  result:= fib(i);
  writeln(i, ' : ', result);
end;

end.