2

这是代码

<?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"; 但我无法弄清楚。它正在杀死我。

4

5 回答 5

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 匹配,以后可以轻松访问。)

于 2012-10-28T23:18:28.123 回答
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/>';

?>
于 2012-10-28T23:20:31.640 回答
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>"; ?>

之后,您可以使用 max,minarray_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>";
于 2012-10-28T23:22:37.400 回答
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;
于 2012-10-28T23:22:48.167 回答
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);
于 2012-10-28T23:25:10.720 回答