Home >Java >javaTutorial >Using Java to output Yang Hui triangle

Using Java to output Yang Hui triangle

高洛峰
高洛峰Original
2016-11-16 11:06:051941browse

This article is used to output Yang Hui triangle. The definition of Yang Hui triangle is that a certain number in it is equal to the sum of the two numbers immediately above it. The effect is as follows:

                                            1 
                                           1 1 
                                          1 2 1 
                                         1 3 3 1 
                                        1 4 6 4 1

Specific code:

public void yanghuiFun() {

        System.out.println("请输入需要打印的行数:");
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();

        if (num > 0) {
            int[][] a = new int[num][num];
            // 将每行的第一个数和最后一个数都赋为1
            for (int i = 0; i < num; i++) {
                a[i][0] = 1;
                a[i][i] = 1;
            }
            // 当行数大于2的时候就可以使用递推公式
            if (num > 2) {
                // 依次将中间某个数的值赋为其上面紧邻着的两个数的和
                for (int i = 2; i < num; i++) {
                    for (int j = 1; j < num - 1; j++) {
                        a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
                    }
                }
            }
            // 依次输出这些数
            for (int i = 0; i < num; i++) {
                // 输出数字前的空格,每行输出的空格数量为:num-1-i
                for (int j = i; j < num - 1; j++) {
                    System.out.print(" ");
                }
                // 开始输出具体的数字以及数字之间的空格
                for (int j = 0; j < i + 1; j++) {
                    System.out.print(a[i][j] + " ");
                }
                System.out.println();
            }
        }
    }


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn