n的介乘函数怎么写,主要是学习递归算法,给出一个例子,并且怎么调用?给出代码马上揭贴!!!(50分)

  • 主题发起人 主题发起人 only_delphi
  • 开始时间 开始时间
O

only_delphi

Unregistered / Unconfirmed
GUEST, unregistred user!
n的介乘函数怎么写,主要是学习递归算法,给出一个例子,并且怎么调用?给出代码马上揭贴!!!
 
function factorial(n: integer): int64;
begin
if n < 1 then
Result := 1
else
Result := n * factorial(n-1);
end;
 
调用:
procedure TForm1.Button2Click(Sender: TObject);
var
a: int64;
begin
a := factorial(5);
ShowMessage(IntToStr(a));
end;
 
kao,我的代码和apw的一样
原来我去一家公司笔试。他们让我做一个10的介乘。我就是这么写的
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Edit2: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
function f(n:integer):int64;
begin
if n<1 then
result:=1
else
result:=n*f(n-1);
end;
begin
edit2.Text:=IntToStr(f(StrToInt(edit1.Text)));
end;

end.
 
10000!,谁来做做,很有意思的
 
如果一定要用递归,算法是对的。
如果真的是为了做n的介乘函数,那么写就不够好,最多也只能算到23的介乘。
 
to :李张柏芝,
那么怎样的方法做n的介乘函数 ?
 
他的意思是把返回值改为 字符串 类型的吧,
这样结果再大也不怕了
 
就是呀,你的整形要加长才行了,呵呵。。。上面的方法不都可取吗?为什么楼主还不结贴呀?
 
多人接受答案了。
 
//递归算阶乘函数 至少可以算到40000的阶乘函数
unit sam10;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
function factorial(n: integer): real;
{ Public declarations }
end;

var
E:int64;
Form1: TForm1;
implementation
{$R *.dfm}

function TForm1.factorial(n: integer): real;
begin
if n < 1 then
Result := 1
else
Result := n * factorial(n-1);
if Result>100000 then
begin
Result := Result/100000;
E := E+5;
end;

end;

procedure TForm1.Button1Click(Sender: TObject);
var
a: real;
begin
E := 0;
a := factorial(40000);
//ShowMessage(IntToStr(a));
Memo1.Lines.Add(FloatToStr(a)+' E'+IntToStr(E));
end;

end.
 
后退
顶部