當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Perl rand()用法及代碼示例


Perl中的rand()函數返回一個介於0和傳遞給它的正數之間的隨機小數,如果未指定任何值,則返回1。除非已經被調用,否則自動調用srand()為隨機數生成器提供種子。

用法: rand(range_value)

參數:
range_value:指定範圍的正數


返回值:
介於0和指定值之間的隨機浮點數

示例1:

#!/usr/bin/perl -w 
  
# Calling the rand function 
$random = rand(15); 
  
# print the random number 
# between 0 and 15 
print("Random Number between 0 and 15: ", 
                          $random, "\n");

輸出:

Random Number between 0 and 15: 12.6694798049858


示例2:

#!/usr/bin/perl -w 
  
# Calling the rand function 
# with negative value 
$random = rand(-25); 
  
# print the random number 
# between 0 and -25 
print("Random Number between 0 and -25: ",  
                           $random, "\n");

輸出:

Random Number between 0 and -25: -7.54296459674615


相關用法


注:本文由純淨天空篩選整理自Code_Mech大神的英文原創作品 Perl | rand() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。