编程语言
首页 > 编程语言> > Java输出杨辉三角

Java输出杨辉三角

作者:互联网

package lanqiao;

public class YangHui {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		 	输出5行杨辉三角
		 	1
		 	1 1
		 	1 2 1
		 	1 3 3 1
		 	1 4 6 4 1
		 */
		int[][] yanghui = new int[5][];		//5表示行数,可以修改
		for(int i = 0 ; i < yanghui.length ; i++) {
			//为一维数组创建空间
			yanghui[i] = new int[i + 1];
			for(int j = 0 ; j <= yanghui[i].length - 1 ; j++) {
				if(j == 0 || j ==yanghui[i].length - 1) {
					yanghui[i][j] = 1;
				}else {
					yanghui[i][j] = yanghui[i - 1][j] + yanghui[i - 1][j - 1];
				}
			}
		}
		//输出杨辉三角
		for(int i = 0 ; i < yanghui.length ; i++) {
			for(int j = 0 ; j < yanghui[i].length ; j++) {
				System.out.print(yanghui[i][j] + " ");
			}
			 //输出换行
			System.out.println();
		}

	}

}

运行结果如下:

 

标签:输出,Java,int,yanghui,杨辉三角,new,public
来源: https://blog.csdn.net/qq_52802699/article/details/122784829