[英]php loop flip coin until 2 heads, then stop
我是 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)
函数用于打印。 事实上,我不知道我是否会打扰任何自定义函数。
您需要声明一个变量来保存函数的return
值。
通过存储当前和之前的抛掷值,您可以编写一个简单的检查,检查是否发生了两个连续的“正面”。
代码:(演示)
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"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.