while
loop
$total = 0; $count = 0;
while ($count < 100) {
$number = mt_rand(0, 100); // get a random number from 0 to 100
$total += $number; $count++;
}
$average = $total / $count;
echo("<p>The total of $count random numbers is " . number_format($total) . " and the average is: " . number_format($average, 2) . "</p>>\n");
The total of 100 random numbers is 5,043 and the average is: 50.43
$rolls = 1;
while (mt_rand(1,6) != 6) { // get a random number from 1 to 6
$rolls++;
}
echo("<p>Number of times to roll a six: $rolls.</p>\n");
Number of times to roll a six: 4.
$total = 0;
$count = 0;
$max = -INF;
while ($count < 10000) {
$rolls = 1;
while (mt_rand(1, 6) != 6) { // get a random number from 1 to 6
$rolls++;
}
$total += $rolls;
$count++;
$max = max($rolls, $max); // get the value of the larger argument
$average = $total / $count;
}
echo("<p>Average: $average Max: $max;</p>\n");
Average: 6.0412 Max: 48;
while
statement, the condition is tested before the while
loop is executed.mt_rand()
and max() functions, which are presented in the chapter 9. The mt_rand()
function gets a random number in the range specified by its arguments. The max()
function gets the larger of the two values that are passed to it as arguments.