Perl中的srand()函數可幫助rand()函數在每次運行程序時生成一個恒定值。
每次調用rand()函數以獲取恒定的隨機值時,此srand()函數使用相同的參數。
用法: srand(seed)
參數:
seed :它是一個整數值。
返回:該函數不返回任何值。
示例1:
#!/usr/bin/perl
# Calling the srand() function and
# Printing a random value
srand(5);
print("The first random number is ", rand(), ".\n");
# Calling the srand() function and
# Printing a random value
srand(5);
print("The second random number is ", rand(), ".\n");
# Calling the srand() function and
# Printing a random value
srand(5);
print("The third random number is ", rand(), ".\n");
# Calling the srand() function and
# Printing a random value
srand(5);
print("The fourth random number is ", rand(), ".\n");
輸出:
The first random number is 0.524839579434232. The second random number is 0.524839579434232. The third random number is 0.524839579434232. The fourth random number is 0.524839579434232.
注意:在上麵的代碼中,可以看出srand()函數的參數是相同的,這就是為什麽rand()函數每次調用時都產生相同的隨機值的原因。
示例2:
#!/usr/bin/perl
# Calling the srand() function and
# Printing a random value
srand(5);
print("The first random number is ", rand(), ".\n");
# Calling the srand() function and
# Printing a random value
srand(6);
print("The second random number is ", rand(), ".\n");
# Calling the srand() function and
# Printing a random value
srand(7);
print("The third random number is ", rand(), ".\n");
# Calling the srand() function and
# Printing a random value
srand(8);
print("The fourth random number is ", rand(), ".\n");
輸出:
The first random number is 0.524839579434232. The second random number is 0.395641888099821. The third random number is 0.266444196765409. The fourth random number is 0.137246505430998.
注意:在上麵的代碼中,可以看出srand()函數具有不同的參數,這就是為什麽rand()函數每次調用時都會產生不同的隨機值的原因。
示例3:
#!/usr/bin/perl
# Printing a random value without calling the srand() function
print("The first random number is ", rand(), ".\n");
# Printing a random value without calling the srand() function
print("The second random number is ", rand(), ".\n");
# Printing a random value without calling the srand() function
print("The third random number is ", rand(), ".\n");
# Printing a random value without calling the srand() function
print("The fourth random number is ", rand(), ".\n");
輸出:
The first random number is 0.241482914266275. The second random number is 0.821264154368208. The third random number is 0.870625858233449. The fourth random number is 0.012084407123389.
注意:在上麵的代碼中,可以看出未使用srand()函數,這就是為什麽rand()函數每次調用時都會產生不同的隨機值的原因。
相關用法
- Perl cos()用法及代碼示例
- Perl each()用法及代碼示例
- Perl int()用法及代碼示例
- Perl log()用法及代碼示例
- Perl abs()用法及代碼示例
- Perl exp用法及代碼示例
- Perl hex用法及代碼示例
- Perl chr()用法及代碼示例
- Perl uc()用法及代碼示例
- Perl sin()用法及代碼示例
- Perl tell()用法及代碼示例
- Perl oct()用法及代碼示例
- Perl ord()用法及代碼示例
- Perl length()用法及代碼示例
- Perl lcfirst()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Perl | srand() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。