Delphi初浅入门笔记之四:过程与函数(函数篇)

与过程不同,函数是有返回值的子程序。一般通过函数名或者一个系统预定义的隐含变量Result返回函数的值。在Delphi中有内部函数和自定义函数两种函数。

标准函数:

标准函数的格式,用StrToInt这个函数类举例:

function StrToInt(const S:String):Interger;

表明该函数接受一个常量参数,并返回一个整型值。

自定函数:

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{

在这里定义了一个CalcFact的函数,函数的返回值是Int64。

}
  function CalcFact(Num:Integer):Int64;
  var
  i,Value:Integer;
  begin
  Value:=1;
  for i:=1 to Num do
      Value:=Value*i;
    Result:=Value;
  end;

{

在这里定义了一个GetSum的函数,返回值为Int64。

}

  function GetSum(V1,V2:Integer):Int64;
  var
  SumV1,SumV2:Int64;
  begin
     SumV1:=CalcFact(V1);//名为CalcFact的函数在这里得到应用
     SumV2:=CalcFact(V2);
     GetSum:=SumV1+SumV2;
  end;

procedure TForm1.Button1Click(Sender: TObject);
Var
Sum:Int64;
Ed1,Ed2:Integer;
begin
   if(edit1.Text='') or (edit2.Text='') then
   begin
       Application.MessageBox('请输入整数','提示:',MB_OK);
       exit;
   end;
   Ed1:=StrToInt(edit1.Text);
   Ed2:=StrToInt(edit2.Text);
   Sum:=GetSum(Ed1,Ed2);//GetSum的函数在这里得到应用
   label1.Caption:=trim(edit1.Text)+'与'+trim(edit2.Text)+'的阶乘和为'+IntToStr(Sum);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
close;
end;

end.

源代码

posted @ 2011-03-02 23:37  橘子西瓜  阅读(623)  评论(0编辑  收藏  举报