FizBuzz program: how to make the output correct?

后端 未结 4 383
梦谈多话
梦谈多话 2021-01-24 15:51

I got a question about this program, it says: The FizzBuzz Challenge: Display numbers from 1 to x, replacing the word \'fizz\' for multiples of 3, \'buzz\' for multiples

相关标签:
4条回答
  • 2021-01-24 16:29

    Use else if so that the conditional don't overlap.

    0 讨论(0)
  • 2021-01-24 16:35

    The problem is of course that when (i % 3 == 0)&&(i % 5 == 0) is true, the two preceding conditions are also true, so you get duplicated output. The easiest way to fix that is to check that the other condition is not true in the first two cases. I.e. make the first condition if((i % 3 == 0)&&(i % 5 != 0)) and the same for the second.

    The other problem with your code is that you're printing the number when any of the cases is true, but you're supposed to print it when none of them are. You can fix that by making a fourth if-condition which checks that none of the conditions are true and if so, prints i.

    Now if you did the above, you'll see that you ended up with some code duplication. If you think about it a bit, you'll see that you can easily fix that, by using if - else if - else if - else, which allows you to assume that the previous conditions were false when the current condition is checked.

    0 讨论(0)
  • 2021-01-24 16:44

    Here's the pseudocode:

    for i in 1 to 100
       if(i % 5 == 0) AND (i % 3 == 0) print 'fizzbuzz'
       else if(i % 3 == 0) print 'fizz'
       else if(i % 5 == 0) print 'buzz'
       else print i
    

    I'll leave it as an exercise for you to convert it into Java, as that might help with the understanding as to how this works.

    0 讨论(0)
  • 2021-01-24 16:50

    Hm, I think I'll only hint:

    1. Think of the correct order: What happens if a number is a multiple of 3, but also of (3 and 5)?
    2. There is an else if statement.
    0 讨论(0)
提交回复
热议问题