1

我正在学习 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 {}
?>
4

3 回答 3

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.
?>
于 2013-10-29T03:47:15.583 回答
1

你不需要有一个 else 语句:

if ($v == $w) {
    echo "<p>It took $rollcount turns until double!</p>";
}

事实上,除非它要执行一组特定的任务,否则您不应该拥有一个。

于 2013-10-29T03:47:27.527 回答
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>";
于 2013-10-29T03:47:10.977 回答