Java循环数模式

时间:2017-11-30 15:43:25

标签: java for-loop

如何为输出执行for循环语句(ii)0 1 1 2 2 2 3 3 3 3 4 4 4 4 4?我似乎无法得到该输出的正确答案。

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

2 个答案:

答案 0 :(得分:1)

现在你已经得到了代码,这是你的错误:

for(int i = 0; i<=4; i++){
    // You´re printing 0 once, so in order to loop you have to loop until j<=i
    for(int j = 0; j<=i; j++){
        // You actually did want to print i here, as it will increment.
        // like 0, 1, 2, 3, 4. in Order to achive your pattern.
        // When printing j it will allways start with 0 again, as it´s the nested loop
        System.out.print(i + " ");
    }
}

现在输出似乎正确

0 1 1 2 2 2 3 3 3 3 4 4 4 4 4 

答案 1 :(得分:0)

要为输出0 1 1 2 2 2 3 3 3 3 4 4 4 4 4编写 a for循环语句,您需要使用OEIS中的A002024序列:

for(int i = 0; i < 15; ++i) {
    System.out.print(((int) Math.floor((1 + Math.sqrt(1 + 8 * i)) / 2) - 1) + " ");
}

您可以对其进行测试here