Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number in delphi

Tags:

random

delphi

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.
like image 361
Caranthir Avatar asked Dec 10 '22 19:12

Caranthir


1 Answers

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

like image 169
Tom Brunberg Avatar answered Dec 20 '22 12:12

Tom Brunberg