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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With