Search code examples
dfizzbuzz

FizzBuzz in Dlang


I'm trying to get fizzbuzz working in D but I have no idea for the life of me what the problem is. I have tried reversing the logic and it does write both words when it is not appropriate, but when it is it just writes nothing.

Here's a screenshot of what the output looks like: http://puu.sh/p67Hd/2a5a598b1b.png

import std.stdio;

void main() {
    for (uint i = 0; i < 100; i++) {
        if (i%5 && i%3) write(i);
        if (!i%3) write("Fizz");
        if (!i%5) write("Buzz");
        writeln();
    }
}

Solution

  • The ! operator has precedence over % so your if statements look like

    if ((!i) % 3) write("Fizz");
    if ((!i) % 5) write("Buzz");
    

    and because all of i is non-zero (besides the first time), !i is always 0 and 0 % 5 and 0 % 3 is always 0 (false).

    To fix, all you need to do is add parenthesis around the % operations

    if (!(i % 3)) write("Fizz");
    if (!(i % 5)) write("Buzz");