php循环抛硬币直到出现2个正面,然后停止

标签 php function loops coin-flipping

我是 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);

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

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

最佳答案

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

您需要声明一个变量来保存函数的返回值。

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

代码:(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"/>

关于php循环抛硬币直到出现2个正面,然后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54776715/

相关文章:

php - 添加计数编码后输出不显示

PHP 和 MySQL 设计 map 搜索站点

将一个比率映射到另一个比率的 Excel 函数名称

r - 如何为包括管道的代码创建循环

linux - 使用 bash 读取文件,然后从提取的单词中执行命令

php - 使用 PHP-MySQLi-Database-Class 的 SQL 查询 rawQuery

php - 查询行中指定列(所有整数)的总和小于指定整数

javascript 函数未被调用/无法从 html 表单工作

list - Clojure 列表成员转换错误

javascript - 通过 Javascript 更改 svg 多边形属性