在delphi中生成随机数

问题描述:

我想在delphi中创建一个随机数,并将其分配为文件作为文件名。我设法做到了,但是当我单击按钮生成数字时,它总是以0开头。任何想法如何解决它

i want to create a random number in delphi and assign it to file as a file name. I managed to do that but when i click button to generate number it always start with a 0. Any idea how to fix it

procedure TForm1.Button1Click(Sender: TObject);
var
test:integer;

begin
test:= random(8686868686868);

edit1.Text:= inttostr(test);
end;

end.


如user246408所述,您应该使用 Randomize 可以使用随机值初始化随机数生成器。另外,如果要将返回的数字限制为正整数,请使用预定义的 MaxInt 常量。

As user246408 said you should use Randomize to initialize the random number generator with a random value. Also if you want to limit the returned numbers to positive integers, use the predefined MaxInt constant.

重载函数返回$ 整数的 System.Random 具有以下签名:

The overloaded function System.Random that returns an integer has the following signature:

  function Random(const ARange: Integer): Integer;

并返回满足以下条件的整数 X 公式 0< = X<范围
为防止值为0,您可以添加一个常量,例如

and returns an integer X which satisfies the formula 0 <= X < ARange. To prevent a 0 value, you can add a constant of your choise, like

procedure TForm17.Button2Click(Sender: TObject);
const
  MinRandomValue = 100000;
var
  test:integer;
begin
  test:= random(MaxInt-MinRandomValue)+MinRandomValue;
  edit1.Text:= inttostr(test);
end;

(从MaxInt中减去MinRandomValue以防止溢出)

(MinRandomValue subtracted from MaxInt to prevent overflow)

或者,您可以使用System.Math.RandomRange

or, you can use System.Math.RandomRange

test := RandomRange(100000, MaxInt);

已记录此处