这是我第一次使用stackoverflow。有了这个,我似乎有一个小问题。这是关于输出19种饮料的代码。使用我当前的代码,它输出以下内容:
19 drinks can serve odd number of guests.
You take 19 down from 19...
18 drinks can serve even number of guests.
You take 18 down from 19...
17 drinks can serve odd number of guests.
You take 17 down from 19...
16 drinks can serve odd number of guests.
相反,它应该输出以下内容:
19 drinks can serve odd number of guests.
You take 1 down from 19...
18 drinks can serve even number of guests.
You take 2 down from 19...
17 drinks can serve odd number of guests.
You take 3 down from 19...
16 drinks can serve odd number of guests.
这是实际的代码。
<?php
$drinks= 19;
for($drinks= 19; $drinks>= 1; $drinks--)
{
if ($drinks % 2)
{
echo '<br />';
echo $drinks. ' drinks can serve odd number of guests. ';
echo '<br />';
echo 'You take ' . $drinks. ' down from 19...';
echo '<br />';
continue;
}
else
{
echo '<br />';
echo $drinks. ' drinks can serve even number of guests. ';
echo '<br />';
echo 'You take ' . $drinks. ' down from 19...';
echo '<br />';
continue;
}
}
?>
我似乎陷入困境。我可以正确处理这个问题吗?
答案 0 :(得分:0)
我建议只定一次饮料数量:
<?php
$drinkNr=19;
for ($drinks= $drinkNr; $drinks> 0; $drinks--)
{
:
// now you can do the text
echo 'You take ' . ($drinkNr - $drinks + 1) . ' down from ' . $drinkNr . '..';
答案 1 :(得分:0)
哎呀。 这是一个简短易用的代码:
<?php
$total = 19;
$i = 1;
for ($c=$total;$c>0;$c--) {
$output = (($c % 2) == 1) ? $c.' drinks can serve odd number of guests' : $c.' drinks can serve even number of guests';
$output .= ($i != $total) ?'<br>You take '.$i.' down from '.$total.'...' : '';
echo $output.'<br>';
$i++;
}
?>
答案 2 :(得分:-1)
$drinks_total = 19;
for($drinks_taken = 1; $drinks_taken <= $drinks_total; $drinks_taken++)
{
if ($drinks_taken % 2)
{
$html = '
<br />
%d drinks can serve even number of guests
<br />
You take %d down from %d...
<br />
';
}
else
{
$html = '
<br />
%d drinks can serve odd number of guests
<br />
You take %d down from %d...
<br />
';
}
echo sprintf($html,$drinks_total - $drinks_taken, $drinks_taken, $drinks_total);
}