我想在delphi中创建一个随机数并将其作为文件名分配给文件。我设法做到了,但是当我单击按钮生成数字时,它总是以 0 开头。不知道如何修复它
procedure TForm1.Button1Click(Sender: TObject);
var
test:integer;
begin
test:= random(8686868686868);
edit1.Text:= inttostr(test);
end;
end.
最佳答案
正如 user246408 所说,您应该使用 Randomize
用随机值初始化随机数生成器。此外,如果要将返回的数字限制为正整数,请使用预定义的 MaxInt
常量。
返回 System.Random
的重载函数 integer
具有以下签名:
function Random(const ARange: Integer): Integer;
并返回一个满足公式
X
的整数 0 <= X < ARange
。为了防止 0 值,您可以添加一个常量,例如
procedure TForm17.Button2Click(Sender: TObject);
const
MinRandomValue = 100000;
var
test:integer;
begin
test:= random(MaxInt-MinRandomValue)+MinRandomValue;
edit1.Text:= inttostr(test);
end;
(从 MaxInt 中减去 MinRandomValue 以防止溢出)
或者,您可以使用 System.Math.RandomRange
test := RandomRange(100000, MaxInt);
记录 here
关于delphi - delphi 生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34481987/