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.
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
Your code has 2 problems.
You don't call Randomize
, that is why you always get zero as the
first "random" value.
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;