【问题标题】:php loop flip coin until 2 heads, then stopphp循环翻转硬币直到2个正面,然后停止
【发布时间】:2019-02-19 23:53:16
【问题描述】:

我是 php 新手,正在尝试编写一个循环,该循环将翻转一枚硬币,直到恰好两个正面都被翻转然后停止。

到目前为止,我已经编写了一个抛硬币的函数:

function cointoss () {
    $cointoss = mt_rand(0,1);
    $headsimg = '<img src=""/>';
    $tailsimg = '<img src=""/>';
    if ($cointoss == 1){
        print $headsimg;
    } else {
        print $tailsimg;
    } 
    return $cointoss;
}

...但我坚持写循环。我尝试了几种方法:

#this code takes forever to load
$twoheads = 0;
for ($twoheads = 1 ; $twoheads <= 20; $twoheads++) {
    $cointoss = mt_rand(0,1);
    cointoss ();
    if ($cointoss == 1) { 
        do {
        cointoss ();
    } while ($cointoss == 1);

    }
}

#one coin flips 
do {
    cointoss ();
} while ($cointoss == 1);

这是一个类的,我们还没有学习数组,所以我需要在没有它们的情况下完成这个。

我了解条件为真时循环执行代码的概念,但不明白当条件不再为真时如何编写。

【问题讨论】:

  • 连续 2 个头?还是一共2个?
  • 继续翻转直到连续两个头,然后停止

标签: php function loops coin-flipping


【解决方案1】:

从“处理函数”内部打印是一个不好的习惯。您可能想声明一个showCoin($toss) 打印函数。事实上,我不知道我是否会为任何自定义函数而烦恼。

您需要声明一个变量,该变量将保存您函数中的return 值。

通过存储当前和之前的投掷值,您可以编写一个简单的检查是否出现了两个连续的“正面”。

代码:(Demo)

function cointoss () {
    return mt_rand(0,1);  // return zero or one
}

$previous_toss = null;
$toss = null;
do {
    if ($toss !== null) {  // only store a new "previous_toss" if not the first iteration
        $previous_toss = $toss;  // store last ieration's value
    }
    $toss = cointoss();  // get current iteration's value
    echo ($toss ? '<img src="heads.jpg"/>' : '<img src="tails.jpg"/>') , "\n";
    //    ^^^^^- if a non-zero/non-falsey value, it is heads, else tails
} while ($previous_toss + $toss != 2);
//       ^^^^^^^^^^^^^^^^^^^^^^- if 1 + 1 then 2 breaks the loop

可能的输出:

<img src="heads.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="heads.jpg"/>
<img src="heads.jpg"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2011-10-16
    相关资源
    最近更新 更多