【问题标题】:How do you print the sequence one 1, then two 2, three 3, ... n ns?如何打印序列一个 1,然后是两个 2,三个 3,... n ns?
【发布时间】:2019-11-07 21:51:05
【问题描述】:

编写一个打印部分序列的程序:

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...

(数字重复多次,等于它)。

我使用了两个for 循环,但是,我不能让 1 打印一次, 2 打印两次,相反,我得到了

1 2 3 4 5 6 1 2 3 4 5 6, etc.

【问题讨论】:

    标签: java loops logic


    【解决方案1】:

    为此,您需要两个 for 循环。

    for (int i = 0; i <= 5; i++) { // This will loop 5 times
        for (int j = 0; j < i; j++) { //This will loop i times
            System.out.print(i);
        }
    }
    

    【讨论】:

      【解决方案2】:

      我记得目标是打印 n 个数字(例如 1 2 2 3 3 3 4 表示 n = 7),按空格分隔。对不起我的 java)),我用 Kotlin 写的,试图改变 Java,但主要思想很清楚。 BTW n – 元素的数量,您需要使用 Scanner 读取。

      int count = 0 //Idea is to create a counter, and to increment it each time of printing
      
      for (int i = 0; i <= n; i++) { //Loops n times
          for (int j = 0; j < i; j++) { //Loops i times
              if (int count < int n) {
              System.out.print(" "+i+" ");
              int count++ //Prints 1 one time, 2 two times, etc. stops if reached n number
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        这个怎么样:

               for(int i=1;i<=num;i++){
                    for(int j=1;j<=i;j++){
                        System.out.print(" "+i+" ");
                    }
                } 
        

        其中,num = 1,2,....n

        (此外,除非您附上代码,否则我们将无法告诉 为什么您得到该输出。请附上代码 sn-ps 以解决此类问题:)!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-24
          • 2021-07-30
          • 1970-01-01
          • 1970-01-01
          • 2019-12-26
          • 2013-11-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多