求 这个 数列 第N项 的值~~!!!!急急急!!!谢谢了!
用自定义函数计算斐波那契数列前N项和(利用2个函数实现)
斐波那契数列如下:1 1 2 3 5 8 13 21 34......
Function F(n:integer):integer;//求第N项的值
Function Sum(n:integer):integer;//求和
谢谢高手了!
[解决办法]
unit Unit3;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TForm3 = class(TForm) ListBox1: TListBox; procedure FormCreate(Sender: TObject); private { Private declarations } Fibo: array of double; public { Public declarations } function GetInt(const AInts: array of double; const Index: Integer): double; function Calc(const N: Cardinal): double; overload; end;var Form3: TForm3;implementation{$R *.dfm}uses math;function TForm3.GetInt(const AInts: array of double; const Index: Integer): double;begin Result := 0; if InRange(Index, Low(AInts), High(AInts)) then Result := AInts[Index];end;function TForm3.Calc(const N: Cardinal): double;var I: Integer;begin SetLength(Fibo, N); with ListBox1.Items do begin BeginUpdate; try Clear; Fibo[0] := 1; for I := 1 to High(Fibo) do begin Fibo[I] := GetInt(Fibo, i - 2) + GetInt(Fibo, i - 1); Add(FormatFloat('#,##0', Fibo[I])); end; finally EndUpdate; end; end; Result := Sum(Fibo);end;procedure TForm3.FormCreate(Sender: TObject);begin Caption := FormatFloat('#,##0', Calc(100) );end;end.
[解决办法]
Function F(const N:UINT):UINT;//求第N项的值var I : Integer; PreResult : Integer; ResultStored : Integer;begin Result := 0; PreResult := 1; for I := 1 to N do begin PreResult := ResultStored; ResultStored := Result; Result := ResultStored + PreResult; end;end;Function Sum(const n:UINT):UINT;//求和begin result := F(N+2)-1;end;
[解决办法]
来个正点的,用递归求解
Function F(N:integer):integer;begin if (N = 2) or (N = 1) then Result := 1 else Result := F(N-1) + F(N-2);end;Function Sum(N:integer):integer;vari : integer;beginResult := 0;For i:= 1 to N do Result := Result + F(i);end;