import java.util.Scanner;
/**
* 问题:输出杨辉三角指定的前几行内容。
*
* @author Administrator
*
* 程序如下:
*
*/
public class PascalTriangle {
public static void main(String args[]){
System.out.println("请输入杨辉三角需要输出的行数,按Enter键结束!");
Scanner s=new Scanner(System.in);
int a=s.nextInt();
System.out.println("杨辉三角的前"+a+"行内容为:");
PascalTriangle pt=new PascalTriangle();
pt.getPascalTriangle(a);
}
public void getPascalTriangle(int x){
//求杨辉三角的前x行内容
int[][] a=new int[x][x];
for(int i=0;i<x;i++){
a[i][0]=1;
a[i][i]=1;
}
for(int i=2;i<x;i++){
for(int j=1;j<x;j++){
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}
//输出杨辉三角的前x行
for(int i=0;i<x;i++){
for(int j=0;j<=i;j++){
System.out.print(a[i][j]+" ");
if(i==j){//进行隔行显示
System.out.println();
}
}
}
}
}
运行结果如下:
run:
请输入杨辉三角需要输出的行数,按Enter键结束!
10
杨辉三角的前10行内容为:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
成功生成(总时间:3 秒)