我正在尝试在 perl 中使用 srand 函数,但似乎它没有经常设置种子值
#!/usr/bin/perl
srand(45);
$int = rand(50);
print "random integer is $int\n";
[root@localhost cookbook]# perl p2.7.pl
random integer is 17.8465963028886
随机数不应该在 45 到 50 之间吗?
最佳答案
srand 种子 随机数生成器。大多数编程语言中的随机数并不是真正的随机数,但对于大多数目的来说都可以。设置种子将允许随机数序列一遍又一遍地重复。从 Perldoc:
[T]here are a few situations where programs are likely to want to call
srand
. One is for generating predictable results, generally for testing or debugging. There, you usesrand($seed)
, with the same$seed
each time.
这是一个示例程序:
#! /usr/bin/env perl
#
use strict; # Lets you know when you misspell variable names
use warnings; # Warns of issues (using undefined variables
use feature qw(say);
srand 10;
for my $count ( (1..6) ) {
say rand 10;
}
每次我运行它时,我都会得到:
$ test.pl
8.78851122762175
7.95806622921617
4.80827281057042
5.25673258208322
4.59162474505394
9.45475794360377
一遍又一遍。那是因为我每次都使用相同的种子,允许随机数函数一遍又一遍地重复。这在测试中很有用。
去掉
srand 10
行,程序每次都会生成不同的随机数序列。根据 Perldoc rand :
Returns a random fractional number greater than or equal to 0 and less than the value of EXPR, [the argument given]. EXPR should be positive.
它继续:
Apply
int()
to the value returned byrand()
if you want random integers instead of random fractional numbers. For example,int(rand(10))
returns a random integer between0
and9
, inclusive.
因此,
rand 50
返回 0 到 50(但不是 50)之间的值。也就是说,int( rand 50 )
将返回一个 0 到 49 之间的整数。如果我想要一个 45 到 50 之间的数字,我必须首先决定 50 是否应该是我想要的数字之一。如果是,我需要六个数字的范围(45、46、47、48、49、50)。因此,我想使用 int( rand 6 )
给我一个 0 到 5 之间的整数。然后我想加上 45 给我 45 的范围,给我 45 到 50 的范围:say 45 + int( rand 6 );
关于perl - perl 中的 srand 函数没有给出正确的值范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772900/