douliang9057 2013-06-20 20:57
浏览 75
已采纳

使用while循环卡在无限循环中的Fizz Buzz脚本 - php [关闭]

I'm trying to write a Fizz Buzz script using a while loop to cycle through the numbers 1-100 and echo each one to the screen.

I'm using the modulus operator to find if a number is a multiple of:

  • 3 in which case it echos Fizz,
  • 5 in which case it echos Buzz,
  • or if its a multiple of both 3 and 5 it echos FizzBuzz

I've written the code below, tested all its parts and it seems to work, but when I run the script, it gets stuck in an infinite loop, echoing Fizz.

$i = 1;

while ($i <= 100) {

    if ((3 % $i) === 0) {
        echo 'Fizz';
        $i = $i++;
    } else if ((5 % $i) === 0) {    
        $i = $i++;
        echo 'Buzz';        
    } else if ( ((3 % $i) === 0) && ((5 % $i) === 0)){
        echo 'FizzBuzz';
    } else {
        echo $i++;
    }

}

Any idea were I went wrong?

  • 写回答

1条回答 默认 最新

  • duandange7480 2013-06-20 21:01
    关注
    $i = 1;
    
    while ($i <= 100) {
    
        $r = '';
    
        if ($i % 3 === 0) {
            $r .= 'Fizz';
        }
    
        if ($i % 5 === 0) {    
            $r .= 'Buzz';        
        }
    
        if (!$r) {
            $r = $i;
        }
    
        echo "$r
    ";
        ++$i;
    }
    

    Online demo: http://ideone.com/WbXZEd

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站