打印杨辉三角

2022/5/5 23:17:02

本文主要是介绍打印杨辉三角,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import java.util.Scanner;



public class Class {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("打印杨辉三角形的行数:");

        int row = scanner.nextInt();

        int[][] a = new int[row][];

        for (int i = 0; i < a.length; i++) {

            a[i] = new int[i + 1];

            for (int j = 1; j <= row - i; j++) {

                System.out.print(" ");

            }

            for (int j = 0; j <= i; j++) { 

                if (j == 0 || j == i) {

                    a[i][j] = 1;

                } else {

                    a[i][j] = a[i - 1][j] + a[i - 1][j - 1];

                }

                System.out.print(a[i][j] + " ");

            }

            System.out.println();

        }

    }

}


这篇关于打印杨辉三角的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程