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.
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
forRandom
range, it exceeds 32-bit boundary and equivalent to2444814356
.if you need just a single "random" value use
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 predefinedMaxInt
constant.The overloaded function
System.Random
that returns aninteger
has the following signature:and returns an integer
X
which satisfies the formula0 <= X < ARange
. To prevent a 0 value, you can add a constant of your choise, like(MinRandomValue subtracted from MaxInt to prevent overflow)
or, you can use System.Math.RandomRange
Documented here