我希望有人能弄明白为什么我的代码不能用于6面骰子,使用数组来计算6000卷的数字。
<?php
// main //////////////////////////////////
//$throw_dice = array();
//$tally = array();
echo "debug - code runs to this point<br>\n";
$throw_dice = throw_dice($throw_dice);
$tally = tally_results($throw_dice);
echo "debug with tally: $tally[4]<br>\n";
exit;
$line = print_table($tally);
echo $line;
// functions ////////////////////////////////
function throw_dice ($f_throw_dice) {
/* required pseudocode:
for loop from 1 to 6000
populate each element with random number 1 - 6
end for loop
return array
*/
for ($i = 0; $i < 6000; $i++) {
$f_throw_dice[] = mt_rand(1,6);
}
return array($f_throw_dice);
}
function tally_results ($f_throw_dice) {
/*
use increment system example shown below with associative array:
$numbers = array(1, 2, 2, 1, 2, 1, 1, 1, 2)
foreach ($numbers as $number) {$tally[$number]++}
will give 5 for $tally[1] and 4 for $tally[2]
*/
//$tally = array('1' => 1,'2' => 2,'3' => 3,'4' => 4,'5' => 5,'6' => 6,);
//$numbers = array($f_throw_dice);
//$tally[0] = '1';
//$tally[1] = '2';
//$tally[2] = '3';
//$tally[3] = '4';
//$tally[4] = '5';
//$tally[5] = '6';
$tally = array();
foreach ($f_throw_dice as $number)
{
$tally[$number]++;
echo $tally;
}
}
function print_table($f_tally) {
/* required pseudocode:
note: concatenate entire formatted printout in one variable $line
Can start this way:
$line = "<pre>";
$line .= sprintf ("DIE #%10s", 'OCCURS');
$line .= "\n===============\n";
sort $f_tally by key
foreach loop
concatenate $line with another $f_tally element using the
sprintf format from last assignment
end loop
return $line
*/
$line = "<pre>";
$line .= sprintf ("DIE #%10s", 'OCCURS');
$line .= "\n===============\n";
ksort ($f_tally);
echo '<ul>';
foreach ($f_tally as $numbers => $tally) {
echo '<pre>',
$line .= sprintf('%s %s', $numbers, $tally), '</pre>';
// echo '<li>$numbers ($tally)</li>';
}
echo '</ul>';
}
?>结果应该如下所示:
DIE # OCCURS
==============
1 1000
2 990
3 1038
4 1012
5 1007
6 953发布于 2015-04-22 02:31:16
几个问题。
1)在throw_dice函数中,更改:
return array($f_throw_dice);...to:
return $f_throw_dice;$f_throw_dice已经是一个数组。因此,通过将其包装在数组函数中,您向数组添加了额外的一层,这会导致tally_results函数中的循环失败。所以,只需按原样return $f_throw_dice即可。
2),并在tally_results函数中,更改:
foreach ($f_throw_dice as $number)
{
$tally[$number]++;
echo $tally;
}...to:
foreach ($f_throw_dice as $number)
{
$tally[$number]++;
}
return $tally;在这里,您不是从函数返回$tally,而是在骰子结果上的每个循环中echo它一次。相反,等待循环结束,然后return它。
3)然后,在print_table函数中,更改:
echo '<ul>';
foreach ($f_tally as $numbers => $tally) {
echo '<pre>',
$line .= sprintf('%s %s', $numbers, $tally), '</pre>';
// echo '<li>$numbers ($tally)</li>';
}
echo '</ul>';...to:
$line .= '<ul>';
foreach ($f_tally as $numbers => $tally) {
$line .= '<pre>';
$line .= sprintf('%s %s', $numbers, $tally) . '</pre>';
// echo '<li>$numbers ($tally)</li>';
}
$line .= '</ul>';
return $line;在这里,你开始构建,然后切换到echoing,再一次,你没有从这个函数返回任何东西。因此,不要对结果进行echo,而是继续在$line变量中捕获它们,然后在函数的末尾回显。
https://stackoverflow.com/questions/29779809
复制相似问题