Randomize Random
在學(xué)習(xí)ProcessMessage函數(shù)時(shí)候看到了這個(gè)代碼,沒用過Randomize函數(shù),所以順便學(xué)習(xí)學(xué)習(xí);
procedure TForm1.Button1Click(Sender: TObject);varI, J, X, Y: Word; beginI := 0;J := 0;while I < 64000 dobeginRandomize;while J < 64000 dobeginY := Random(J);Inc(J);end;X := Random(I);Inc(I);end;Canvas.TextOut(10, 10, 'The Button1Click handler is finished');end;
這個(gè)函數(shù)在幫助里面的原說明如下:
Initializes the random number generator with a random value.
前面的Initializes the random number generator 應(yīng)該翻譯為:初始化隨機(jī)數(shù)產(chǎn)生器? 這應(yīng)該是沒錯(cuò)的,但with a random value 怎么翻譯呢,用一個(gè)隨機(jī)值?接著往下看,下面還有個(gè)Y:=Random(J);會(huì)不會(huì)跟這個(gè)函數(shù)有關(guān)系?繼續(xù)查random()函數(shù):
Generates random numbers within a specified range.//翻譯為:在指定的范圍內(nèi)產(chǎn)生隨機(jī)數(shù)
Delphi syntax:
function Random [ ( Range: Integer) ];
下面還有更詳細(xì)的說明:
In Delphi code, Random returns a random number within the range 0 <= X < Range. If Range is not specified, the result is a real-type random number within the range
0 <= X < 1.
?
到此,我還是看不出來這兩個(gè)函數(shù)有什么關(guān)系,再看一下Randomize 的description:
Description
Randomize initializes the built-in random number generator with a random value (obtained from the system clock). The random number generator should be initialized by making a call to Randomize, or by assigning a value to RandSeed.
{Randomize 用一個(gè)隨機(jī)值來初始化內(nèi)置的隨即數(shù)產(chǎn)生器(這個(gè)隨機(jī)值來自于系統(tǒng)時(shí)鐘)。隨即數(shù)產(chǎn)生器通過調(diào)用Randomize函數(shù)或指定RandSeed變量來進(jìn)行初始化。}
Do not combine the call to Randomize in a loop with calls to the Random function. Typically, Randomize is called only once, before all calls to Random.
{不要在同一層循環(huán)內(nèi)同時(shí)調(diào)用Randomize和Random函數(shù)。典型的應(yīng)用是,在所有的random函數(shù)前調(diào)用一次Randomize}
?
我的理解是,隨即數(shù)的產(chǎn)生是要根據(jù)系統(tǒng)時(shí)鐘進(jìn)行變化的,randomize的作用就是將 the built-in random number generator 和系統(tǒng)時(shí)鐘掛鉤,接下來的random函數(shù)才會(huì)起作用。
?
靠理論不行,寫個(gè)例子:
procedure TForm1.bt_3Click(Sender: TObject); vari:Integer; begin//Randomize;Memo_1.Lines.Clear;for i := 1 to 100 doMemo_1.Lines.Add(IntToStr(Random(100))); end;
注銷randomize,運(yùn)行,沒什么問題啊,照樣變化!
把注銷去掉,運(yùn)行,也能變化!
怎么回事,d7合二為一了?
放到d5下,還是一樣!
怎么回事?
到網(wǎng)上一查,是去掉randomize后,運(yùn)行幾次的隨即數(shù)取值都相同,而不是在一次運(yùn)行期間的數(shù)據(jù)變化不變。仔細(xì)看了一下,果然如此。
到此,這兩個(gè)函數(shù)我搞明白了。
明白是明白了,可是,以前都是直接寫Random沒有randomize!汗!還好那個(gè)數(shù)據(jù)的重復(fù)率幾乎為0,要不麻煩大了。
以后還是多看看書,多看看別人的代碼。
總結(jié)
以上是生活随笔為你收集整理的Randomize Random的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 头疼,不停的头疼.
- 下一篇: 软件需求工程 高校教学平台 前景与范围