java绘制杨辉三角

1.运行结果如下:

2.代码如下

import java.util.Scanner;

public class Triangle {

        public static void main(String[] args) {

                int[][] yh = new int[4][];
                for (int i = 0; i < yh.length; i++) {
                    for (int j = 0; j < yh.length - i - 1; j++) {
                        //打印空格
                        System.out.print(" ");
                    }
                    //给每个二维数据的元素赋值一维数组
                    yh[i] = new int[i + 1];
                    for (int j = 0; j < yh[i].length; j++) {
                        if (j == 0 || i == j) {
                            yh[i][j] = 1;
                        } else {
                            yh[i][j] = yh[i - 1][j] + yh[i - 1][j - 1];
                        }
                        //格式化输出
                        System.out.printf("%3d", yh[i][j]);
                    }
                    //换行
                    System.out.println();
                }
                System.out.println();
            }}


猜你喜欢

转载自blog.csdn.net/weixin_52563520/article/details/128648889