如何为随机数生成创建循环或限制?我需要(0,100)中的30个随机数。
我知道我可以使用rand(0,100)
来生成一般的数字。但是我需要使这种情况发生30次,然后才能整理数据。
数字的重复是没有问题的,但是我还需要将值排序为x <50和x> 50。知道如何在生成后如何将数组中的数字分为2个单独的组吗?
答案 0 :(得分:0)
尝试一下:
$lessFifty = array(); // Array to hold less than fifty numbers
$moreFifty = array(); // Array to hold more than fifty numbers
for ($i = 1; $i<=30; $i++) {
$number = rand(0, 100); // Variable $number holds random number
// Conditional statements
if ($number < 50 ) { // Check if value is less than fifty
$lessFifty[] = $number; // Add number to this array
} else { // Check if value is greater than fifty
$moreFifty[] = $number; // Add number to this array
}
}
// Display numbers in arrays
print_r($lessFifty);
print_r($moreFifty);
for循环将运行rand() function
30次,并将生成的每个随机数插入数组$randomNum
。
您还可以使用while
或do while
循环执行相同的操作。由您决定。