Java

怎么用java输出等腰杨辉三角

小亿
153
2024-04-26 16:40:46
栏目: 编程语言

下面是一个用Java输出等腰杨辉三角的示例代码:

import java.util.Scanner;

public class YangHuiTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入杨辉三角的行数:");
        int numRows = scanner.nextInt();

        int[][] triangle = new int[numRows][];

        for (int i = 0; i < numRows; i++) {
            triangle[i] = new int[i + 1];
            triangle[i][0] = 1;
            triangle[i][i] = 1;

            for (int j = 1; j < i; j++) {
                triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
            }
        }

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < numRows - i - 1; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                System.out.print(triangle[i][j] + " ");
            }
            System.out.println();
        }
    }
}

运行这个代码,输入要输出的杨辉三角的行数,程序会输出相应行数的等腰杨辉三角形状。

0
看了该问题的人还看了