编写程序打印帕斯卡三角。

//用户输入打印的杨辉三角的行数line,输出:打印杨辉三角(每个数字的宽度是4.)
package printPascalTriangle2;

import java.util.Scanner;

public class PrintPascalTriangle2 {

    
    public static void main(String[] args) {
        
        Scanner console = new Scanner(System.in);
        System.out.print("input the lines > 1:");
        int line = console.nextInt();
        
        printNext(line);
        

    }
    
    public static void printNext(int line)
    {
        //计算数值
        int [][]s =new int[line][line];
         for(int i=0;i <= line-1;i++)
         {
            for(int j = 0;j <= i;j++) 
            {
               if(j==0||j==i)
                 s[i][j]=1;
               else
                 s[i][j] = s[i-1][j-1] + s[i-1][j];
            }
           
         }
         //打印
          for(int i=0;i <= line-1;i++)
         {
            for(int j = 1;j <= (line-i-1) * 2;j++)
               System.out.print(" ");
            for(int k = 0;k <= i;k++) 
                  System.out.printf("%4d",s[i][k]);
            System.out.println();
         }
    }

}//class

 

posted on 2014-03-15 09:44  Sweet Smile  阅读(741)  评论(0编辑  收藏  举报