日期:2014-05-20  浏览次数:20681 次

杨辉三角问题2
 

import javax.swing.JOptionPane;

public class test3 {  
  
   
  public static void main(String[] args) {  
  
  String num=JOptionPane.showInputDialog("请输入杨辉三角形的行数:50以内的数字");  
  try{
  int fei= Integer.parseInt(num);
  }
  catch (NumberFormatException e){
 
  System.out.println("请输入数字,不可为空");
  return;
  }
  int n = Integer.valueOf(num); 
  String hou ="%16d";
  String xiao =" ";  
  //String ff=" ";
  Long c=0l;
  if(n>50)
  System.out.print("请输入正确的值");
   
  else {
  /* if(n<=10){ hou="%6d"; xiao=" ";}
  else if(n<=20){ hou="%10d"; xiao=" ";}
  else if(n<=30) {hou="%12d"; xiao=" ";}
  else if(n<=40) {hou="%14d"; xiao=" ";} */
   
   
  long[][] a=new long[n][n];  
   
   
  for(int i=0;i<n;i++)  
  {  
  a[i][0]=1;  
  a[i][i]=1;  
  }  
   
   
  for(int i=2;i<n;i++) {
  for(int j=1;j<i;j++) {
  a[i][j]=a[i-1][j-1]+a[i-1][j];
  c = (a[i][j/2]);}
  }  
   
   
   
  String d = c.toString();
  for (int e =1; e<=d.length(); ++e){
  hou="%"+(e+1)+"d";
  xiao=" ";
   
  }
   
  for(int i=0;i<n;i++)  
  {  
  //打印空格  
  for(int k=0;k<n-i;++k)  
  System.out.print(xiao);  
  //打印数字  
  for(int j=0;j<=i;j++)  
  System.out.printf(hou,a[i][j]);  
   
  System.out.println(" ");
  //换行  
  System.out.println();  
  }  
  }
  }
}

  1  

  1 1  

  1 2 1  

  1 3 3 1  

  1 4 6 4 1  

这是5行时候结果

  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  



这是10行结果

如何让空格也动态变化 望大神教教




  



------解决方案--------------------