1

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();
    }
}
sigod
  • 3,514
  • 2
  • 21
  • 44
Scy
  • 245
  • 1
  • 12

2 Answers2

3

The reason is the operator precedence in D.

The if(!i%3) will actually be interpreted as if((!i)%3), which results in either 0%3 (which is false), or 1%3 (which is true). !n will result in 1 if n is 0, otherwise it will always be 0. Because it's going from 0 to 100, (!i) % 3 will only be true once at the beginning. This is the reason why there is a FizzBuzz at the start of the output.

So instead your code should look like this:

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();
    }
}
Max Alibaev
  • 681
  • 7
  • 17
WebFreak001
  • 2,415
  • 1
  • 15
  • 24
3

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");
Max Alibaev
  • 681
  • 7
  • 17
kmdreko
  • 42,554
  • 6
  • 57
  • 106