設定隨機數范圍, 返回數組長度, 得到一組不重復的隨機數 [delphi] unit Unit11; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm11 = class(TForm) btn1: TButton; procedure btn1Click(Sender: TObject); private //生成的隨機數函數 function CreateRandom(const RangeStart, RangeEnd, ResultCount: integer): Tarray<Integer>; { Private declarations } public { Public declarations } end; var Form11: TForm11; implementation {$R *.dfm} //CreateRandom(隨機數取值范圍起始值, 終止值; 返回數組長度) function TForm11.CreateRandom(const RangeStart, RangeEnd, ResultCount : integer) : Tarray<Integer>; var tmpLst : TStringList; //可以使用泛型列表或數組代替 I, n: Integer; begin if RangeStart >= RangeEnd then raise Exception.Create('錯誤的隨機數范圍!'); if ResultCount < 1 then raise Exception.Create('隨機數返回數組長度必須大於0!'); tmpLst := TStringList.Create; tmpLst.Capacity := RangeEnd - RangeStart; try for n := RangeStart to RangeEnd do begin tmpLst.Add(IntToStr(n)); end; Randomize; SetLength(Result, ResultCount); for I := 0 to ResultCount do begin n := Random(tmpLst.Count - 1); Result[i] := StrToInt(tmpLst.Strings[n]); tmpLst.Delete(n); end; finally tmpLst.free; end; end; procedure TForm11.btn1Click(Sender: TObject); var MyArr : Tarray<Integer>; I : Integer; s : string; begin s := ''; MyArr := CreateRandom(0, 100, 10); for I := Low(MyArr) to High(MyArr) do s := s + inttostr(Myarr[i]) + ' '; ShowMessage(s); s := ''; MyArr := CreateRandom(100, 1000, 15); for I := Low(MyArr) to High(MyArr) do s := s + inttostr(Myarr[i]) + ' '; ShowMessage(s); end; end.