Delphi 递归

由于delphi的过程比较简单,因此重点学习函数,函数中最难的是递归,本文通过实例来学习。

  框图界面如下:

   

 代码如下:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);

    function Fibonacci(n:integer):integer;
    procedure Edit1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
     str1:string;
     ff:Integer;
begin
     str1:=Edit1.Text;
     ff:=Fibonacci(strtoint(str1));
     //showMessage(inttostr(ff));
     Edit1.Text:=inttostr(ff);
end;

function TForm1.Fibonacci(n:integer):integer;
begin
  if n<1 then result:=1                         //result 是返回值
  else result:=Fibonacci(n-1)+Fibonacci(n-2)
end;
procedure TForm1.Edit1Click(Sender: TObject);
begin
    Edit1.Text:='';
end;

end.

 运行结果如下:

猜你喜欢

转载自blog.csdn.net/weixin_42528089/article/details/84192972