【发布时间】:2021-12-22 13:01:17
【问题描述】:
所以,我一直在尝试为“骰子生成器”编写代码,我希望它生成随机数(从 1 到 6)x 次。 x 的次数由用户通过终端作为参数给出,使用这个“$argc argv”函数,但这并不重要。
我想知道的是:如何生成随机值x次?
举例:
用户输入:4
输出:5 3 6 8
用户输入:3
输出:5 1 2
这就是我想要写的。我用array_rand函数,以数组为参数,第二个参数是我想要的次数,但是不行!我在这里没有得到什么?
<?php
if ($argc < 2) {
print "You have to write at least one parameter" .PHP_EOL;
exit(1);
}
//This is the variable that corresponds to the number of times the user will give on the Terminal as a parameter.
//$randoms = $argv[1];
$num = 3;
$diceNumbers = [1, 2, 3, 4, 5, 6];
$keys = array_rand($diceNumbers, $num);
print $diceNumbers[$keys[0]]." ".$diceNumbers[$keys[1]] .PHP_EOL;
?>
【问题讨论】:
-
没有理由,它似乎并没有以这种方式工作! :D 它总是只返回 2 个随机值,而不是我想要的数字
-
但是你只输出两个值。
$diceNumbers[$keys[2]]也存在。