Max,Min和sum随机数php

时间:2012-10-28 23:16:22

标签: php

这是代码

<?php
echo "<table border=\"0\">";
for ($d = 1; $d <= $times;$d++ )
 {
echo "<tr><td>";
echo  rand(1,6), "\n";
echo "</td></tr>";
} 
echo "</table>"; ?>

我试图获得rand(1,6), "\n";的最大值,最小值和总和值 但我无法弄明白。它杀了我。

5 个答案:

答案 0 :(得分:2)

$rands = array(); // rand() storage
for($d = 1; $d <= $times; $d++){
    $rands[$d] = rand(1, 6); // store rands
}
var_dump($min = min($rands)); // min() of rands
var_dump($min = max($rands)); // max() of rands

^参见示例代码。

PS :我使用[$d],因为他有一个基于1的增量,可能需要他的进一步逻辑。这样rands键匹配他的$ d​​,可以是以后很容易访问。)

答案 1 :(得分:1)

<?php

$min = 10;
$max = -1;
$sum = 0;

for ($d = 1; $d <= $times; $d++) {
    $n = rand(1, 6);
    if ($n < $min) $min = $n;
    if ($n > $max) $max = $n;
    $sum += $n;
}

echo $min . ' ' . $max . ' ' . $sum . '<br/>';

?>

答案 2 :(得分:1)

您还需要收集数组中的随机数:

echo "<table border=\"0\">";
$rands = array();
#################
for ($d = 1; $d <= $times; $d++)
{
    echo "<tr><td>";
    echo $rands[] = rand(1,6), "\n"; 
         ###########
    echo "</td></tr>";
} 
echo "</table>"; ?>

之后,您可以使用maxminarray_sum(所有这些链接都附带了很好的示例)。

正如您的代码已经显示的那样,您应该开始区分执行数据处理的代码和执行HTML输出的代码:

// handle the data

$randomNumbers = array();
foreach (range(1, $times) as $d)
{
    $randomNumbers[$d] = rand(1,6);
}


// output the data

echo '<table border="0">';
foreach ($randomNumbers as $number) {
    printf("<tr><td>%d</tr></td>", $number);
}
echo "</table>";

答案 3 :(得分:0)

$sum=0; 
for ($d = 1; $d <= $times;$d++ ) { 
  echo "<tr><td>";  
  $r=rand(1,6);
  $sum +=$r;
  echo  "$r, \n"; 
  echo "</td></tr>"; 
  if ($d==1) { $min=$r; $max=$r; } 
  if ($r>$max) $max=$r;
  if ($r<$min) $min=$r;
} 
// do something with $min, $max and $sum;

答案 4 :(得分:0)

<?php      
  $total = 0;
  echo "<table border=\"0\">";

  for ($d = 1; $d <= $times;$d++ )
  { 
       $rand = rand(1,6);
       $total += $rand;    
       $array[] = $rand;

       echo "<tr><td>";
       echo  $rand, "\n";
       echo "</td></tr>";
  } 
echo "</table>"; ?>

echo $total;
echo min($array);
echo max($array);