在一次练习中,我将 while 循环与 if/else 子句结合起来,因此决定将 if/else 转换为使用 switch 语句,只是为了挑战我的想法。
程序很简单:有两名玩家必须连续赢得 3 场比赛才能停止比赛。球员值在 0 和 1 之间随机排序,配对比赛有一个上限,以防随机性赢得比赛:)
我想了解哪个是最好的解决方案,以及为什么,因为在我看来,switch 版本似乎只需要几行代码!
<?php
$playerA=0;
$playerB=0;
$winA=0;
$winB=0;
$pair=0;
while ($winA<=2 && $winB<=2 && $pair<=15) {
$playerA = rand(0,1);
$playerB = rand(0,1);
if ($playerA > $playerB) {
$winA ++;
$winB=0;
echo "<div>Player A Wins.</div>";
} elseif ($playerA < $playerB) {
$winB ++;
$winA=0;
echo "<div>Player B Wins.</div>";
} elseif ($playerA == $playerB) {
$pair ++;
$winA=0;
$winB=0;
echo "<div>Pair, play again!</div>";
}
}
echo "<div>There is a total of {$pair} pair matches</div>";
?>
现在开关一...
<?php
$playerA=0;
$playerB=0;
$winA=0;
$winB=0;
$pair=0;
while ($winA<=2 && $winB<=2 && $pair<=15) {
$playerA = rand(0,1);
$playerB = rand(0,1);
switch ($playerA && $playerB):
//This is an error: it should have been switch(true)
case ($playerA > $playerB):
$winA++;
$winB=0;
echo "<div>Player A Wins.</div>";
break;
case ($playerA < $playerB):
$winB++;
$winA=0;
echo "<div>Player B Wins.</div>";
break;
case ($playerA == $playerB):
$pair++;
$winA=0;
$winB=0;
echo "<div>Pair, Play again!</div>";
break;
endswitch;
}
echo "<div>There is a total of {$pair} pair matches</div>";
?>