当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Perl srand()用法及代码示例


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()函数每次调用时都会产生不同的随机值的原因。



相关用法


注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 Perl | srand() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。