以下是杨辉三角的Java代码:

import java.util.Scanner;

public class YangHuiTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要打印的行数:");
        int n = scanner.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();
        }
    }
}

运行之后,输入要打印的行数,例如输入5,会输出以下内容:

请输入要打印的行数:
5
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
``
杨辉三角java代码么

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

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