简体   繁体   English

如何仅使用两个变量在java中制作数字模式?

[英]How to make pattern of numbers in java using only two variables?

#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15

this is the required pattern and the code which i used is这是所需的模式,我使用的代码是

  public class Test{
    public static void main(String[] args) {
        int k = 1;
        for (int i = 0; i <= 5; i++){
            for (int j = 1; j <= i; j++){
                System.out.print(k + " ");
                k++;
            }
            System.out.println();
        }
    }
}

as you can see i used the variable k to print the numbers.如您所见,我使用变量k来打印数字。 My question is that is there a way to print the exact same pattern without using the third variable k ?我的问题是有没有办法在不使用第三个变量k 的情况下打印完全相同的模式? I want to print the pattern using only i and j .我想只使用ij打印图案。

Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:由于这个问题被制定为一个学习练习,我不会提供一个完整的解决方案,而是一些提示:

  • Could you print the sequence if you knew the last number from the prior line?如果你知道前一行的最后一个数字,你能打印出序列吗? - the answer is trivial: you would need to print priorLine + j - 答案很简单:你需要打印priorLine + j
  • Given i , how would you find the value of the last number printed on i-1 lines?给定i ,您将如何找到i-1行上打印的最后一个数字的值? - to find the answer, look up the formula for computing the sum of arithmetic sequence . - 要找到答案,请查找计算等差数列之和公式 In your case d=1 and a 1 =1.在您的情况下,d=1 和 a 1 =1。

You can use this:你可以使用这个:

public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 0; j < i; j++) {
            System.out.print((i * (i - 1)) / 2 + j + 1 + " ");
        }
    }
}

Or you can the find the nth term and subtract it each time:或者你可以找到第 n 项并每次减去它:

public static void main(String[] args) {
    for (int i = 0; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(((i * (i + 1)) / 2) - (i - j) + " ");
           // k++;
        }
        System.out.println(" ");
    }
}

You can use您可以使用

System.out.println((i+j) + " ");

eg例如

i    j    (i+j)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM