PHP FizzBuzz Logic

2020-03-30 05:01发布

When we write the fizzbuzz script, why are we testing to see if it is equal to 0? Or am I misunderstanding?

Example: $i % 3 == 0

<?php
for ($i=1; $i<=100; $i++) {
    if ($i%3==0 && $i%5==0) {
        echo 'FizzBuzz';
    }else if($i%3==0){
        echo 'Fizz';
    }else if($i%5==0){
        echo 'Buzz';
    }else{
        echo $i;
    }
    echo "\n";
}

3条回答
Explosion°爆炸
2楼-- · 2020-03-30 05:35
<?php
array_map(function($l) {
  echo $l . PHP_EOL;
}, array_map(function($i) {
  $is_fizz = ($i % 3) === 0;
  $is_buzz = ($i % 5) === 0;
  return (!$is_fizz && !$is_buzz) ? $i : 
    ($is_fizz ? 'Fizz' : '') . ($is_buzz ? 'Buzz' : '');
}, range(1 , 100)));
查看更多
欢心
3楼-- · 2020-03-30 05:41

A more concise but harder to read solution:

for ($i=1;$i<=100;$i++) { 
    print ( (fmod(($i/3),1)  ?  '' : "fizz") . (fmod(($i/5),1)  ?  '' : "buzz")  ?:  ("$i") ) ."\n"; 
}
查看更多
倾城 Initia
4楼-- · 2020-03-30 05:51

The program fizzbuzz prints 'fizz' if a number is divisible by 3, 'buzz' if a number is divisible by 5, and 'fizzbuzz' if a number is divisible by both.

Your program is not checking if the numbers are equal to 0, instead it is using the modulo operator to check if the remainders are 0.

$i%3==0 means number is divisible by 3

$i%5==0 means number is divisible by 5

$i%5==0 && $i%3==0 means the number is divisible by both

查看更多
登录 后发表回答