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

使用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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化