import java.util.Scanner; public class Yanghui { public static void main(String[] args) { System.out.print("请输入你要打印的杨辉三角的层数:"); Scanner sc = new Scanner(System.in); sc.close(); int height =sc.nextInt(); //杨辉三角的高度(层数) int row = 2*height-1; int[ ][ ] yh = new int[height][row]; int j=0; int temp_row=row-1; for(int i=height-1;i>=0;i--) { yh[i][j++]=1; //将左面一斜排的值全设为1 yh[i][temp_row--]=1; //将右面一斜排的值全设为1 } for(int i=2;i<height;i++) { for(j=height-1-i+2;j<row-2;j+=2) //对某一行而言,得到除首尾为1之外的其他值 { yh[i][j]=yh[i-1][j-1]+yh[i-1][j+1]; } } for(int m=0;m<height;m++) { for(int n=0;n<row;n++) { if(yh[m][n]==0) System.out.print(" "); else System.out.print(yh[m][n]); } System.out.println(); } } }
原文地址:http://blog.csdn.net/huolang_vip/article/details/41925779