以下是一个用 Java 编写的杨辉三角代码:

import java.util.Scanner;

public class YangHuiTriangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print('请输入需要打印的杨辉三角行数:');
        int n = sc.nextInt();
        int[][] arr = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    arr[i][j] = 1;
                } else {
                    arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
                }
                System.out.print(arr[i][j] + ' ');
            }
            System.out.println();
        }
    }
}

以上代码实现了输入行数 n,输出 n 行的杨辉三角。其中,二维数组 arr 存储了每个位置的值,通过两层循环来计算每个位置的值并输出。


原文地址: https://www.cveoy.top/t/topic/oev2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录