FizBuzz程序:如何使输出正确? [英] FizBuzz program: how to make the output correct?

查看:138
本文介绍了FizBuzz程序:如何使输出正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个程序有一个疑问,它说: FizzBu​​zz挑战:显示从1到x的数字,用单词'fizz'表示3的倍数,'buzz'表示5的倍数和'fizzbuzz'结果3和5的倍数.结果必须是:1 2嘶嘶声4嗡嗡声嘶嘶声7 8嘶嘶声嗡嗡声11嘶嘶声13 14嘶嘶声16 ...

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 of 5 and 'fizzbuzz' for multiples of both 3 and 5. Th result must be:1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 ...

所以我的问题是在打印输出时,我不知道该怎么办.

So my problem is at the time to print the output, I dont know what to do.

public class Multiplos {

    public static void main(String args[]) {

        for (int i = 1; i <= 100; i++) {

            if (i % 3 == 0) {
                System.out.print(i + " ");
                System.out.print(" fizz ");
            }

            if (i % 5 == 0) {
                System.out.print(" " + i);
                System.out.print(" " + "buzz ");
            }

            if((i % 3 == 0)&&(i % 5 == 0)){
                System.out.print(i + " ");
                System.out.print(" fizzbuzz ");
            }

        }

    }
}

推荐答案

这是伪代码:

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

我将保留它作为将其转换为Java的练习,因为这可能有助于理解它的工作原理.

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.

这篇关于FizBuzz程序:如何使输出正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆