我正在学习PHP并尝试编写一个小骰子循环。我想知道如何用更合适的语法重写它:
<?php
$rollcount = 1;
do {
$v = rand(1, 6);
$w = rand(1, 6);
$rollcount++;
echo "<p>$v, $w</p>";
}
while ($v != $w);
if ($v == $w) {
echo "<p>It took $rollcount turns until double!</p>";
} else {}
?>
答案 0 :(得分:3)
如果不执行任何操作,只需删除该else子句
else {}
你甚至不需要那个if
陈述,因为控制权只有在两者相等时才会到达那里。
<?php
$rollcount = 1;
do {
$v = rand(1, 6);
$w = rand(1, 6);
$rollcount++;
echo "<p>$v, $w</p>";
}
while ($v != $w);
echo "<p>It took $rollcount turns until double!</p>"; // that `if` was no needed here. Its implied.
?>
答案 1 :(得分:1)
您不需要另外声明:
if ($v == $w) {
echo "<p>It took $rollcount turns until double!</p>";
}
如果确实如此,除非它要执行一组特定的任务,否则你不应该有一个。
答案 2 :(得分:0)
$rollcount = 0;
while(true){
++$rollcount;
$v = rand(1,6);
$w = rand(1,6);
echo "<p>".$v.", ".$w."</p>";
if($v === $w){
break;
}
}
echo "<p>It took ".$rollcount." turns until double!</p>";