close
有時我們要隋機取得一些亂數,這時rand可以做到這樣的功能,,以下用簡單的範子來簡單的說明之:
rand 有二種寫法(perl真是自由><) 第一種語法如下:
rand 某數 :這樣會取得 0~某數 之間的亂數 而某數可以是整數也可以是浮點數 
上以是取得0~某數的亂數 但如果要取得0~1 之間的亂數呢? 就要用 rand 即可 很簡單吧,不知有何種語言可以用如此簡短的語法到做這樣的功能 !!
以下看一看簡單的範例

#!/bin/perl
my $rand1=rand 3;
print "0~3's is :$rand1 :" ;
my $rand2=rand ;
print "0~1's rand is :$rand2\n" ;

下面是執行三次的結果
0~3's is :2.18845155531291 :0~1's rand is :0.408041716410906
0~3's is :1.9211506130987 :0~1's rand is :0.12311837644981
0~3's is :2.13329441704537 :0~1's rand is :0.823874051773117

如果要取得的亂數都是整數可以用int 這個function來處理
#!/bin/perl
my $rand1=int (rand 3)+1;
print "0~3's is :$rand1\n" ;


0~3's is :1
0~3's is :2
0~3's is :1
arrow
arrow
    全站熱搜

    yuanann 發表在 痞客邦 留言(0) 人氣()