FizzBuzz test in Javascript

1

I'm trying to test the "FIZZBUZZ" which consists of the following:

  

Write a program that prints the numbers from 1 to 100. But for   multiples of three print "Fizz" instead of the number and for the   multiples of five print "Buzz". For numbers which are multiples of   both three and five print "FizzBuzz".

I wrote the following code, but it is not working! Can someone give me a light?

var n = 1;

while (n <= 100) {
    if ((n % 3) == 0 || (n % 5) == 0) {
        if ((n % 3) == 0 && (n % 5) == 0) {
            console.log("FizzBuzz");
        }
        else if (n % 3 == 0 && (n % 5) !== 0) {
            console.log("Fizz");
        }
        else if ((n % 5) == 0 && (n % 3) !== 0) {
            console.log("Buzz");
        }
    else {
        console.log(n);
    }
    }
n = n + 1;
}

If you have suggestions on how to make my code clearer, you will be very welcome!

    
asked by anonymous 29.10.2015 / 13:21

2 answers

2

Numbers that are not multiples of 3 or 5 are not printed because they are within the first if and there is no console.log for them.

if ((n % 3) == 0 || (n % 5) == 0) {

    } else {
       console.log(n);
    } <-- os demais números depois dessa linha, que não tem nenhum console.log
    n = n + 1;
} 

Suggestion:

var n = 1;

while (n <= 100) {
    if(n % 3 == 0 && n % 5 == 0){
        console.log(n +" FizzBuzz");
    }else if(n % 5 == 0){
        console.log(n +" Buzz");
    }else if(n % 3 == 0){
        console.log(n +" Fizz");
    }
    n++;
}
    
29.10.2015 / 13:41
1

I was able to find the problem with my code! It was all about a wrong place! To make it documented, the functional code looks like this:

var n = 1;

while (n <= 100) {
    if ((n % 3) == 0 || (n % 5) == 0) {
        if ((n % 3) == 0 && (n % 5) == 0) {
            console.log("FizzBuzz");
        }
        else if (n % 3 == 0 && (n % 5) !== 0) {
            console.log("Fizz");
        }
        else if ((n % 5) == 0 && (n % 3) !== 0) {
            console.log("Buzz");
        }
    }
    else {
        console.log(n);
    }
n = n + 1;
}

Not the most elegant solution. But solve the problem! Hugs to all!

    
29.10.2015 / 13:40