Generate random number in delphi

2019-08-11 19:56发布

问题:

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.

回答1:

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.

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

  function Random(const ARange: Integer): Integer;

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;

(MinRandomValue subtracted from MaxInt to prevent overflow)

or, you can use System.Math.RandomRange

test := RandomRange(100000, MaxInt);

Documented here



回答2:

Your code has 2 problems.

  1. You don't call Randomize, that is why you always get zero as the first "random" value.

  2. You use too large value 8686868686868 for Random range, it exceeds 32-bit boundary and equivalent to 2444814356.

if you need just a single "random" value use

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

begin
  Randomize;
  test:= random($7FFFFFFF);

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


标签: delphi random