实验四:采用一维数组输出等腰三角形的杨辉三角。
1.程序代码:
1 package YANGHUI; 2 3 import java.util.Scanner; 4 5 public class YANGHUI { 6 7 public static int[] printYangHui(int col){ 8 9 int space=(col+1)*col/2; 10 int[] a=new int[space+1]; 11 a[0]=space; 12 a[1]=1; 13 a[2]=1; 14 a[3]=1; 15 16 int count=2; 17 18 for(int i=3;i<=col;i++){ 19 count++; 20 int flag=i*(i-1)/2; 21 for(int j=1;j<=count;j++){ 22 if(j==1||j==count){ 23 a[flag+j]=1; 24 }else{ 25 a[flag+j]=a[(i-2)*(i-1)/2+(j-1)] + a[(i-2)*(i-1)/2+j]; 26 } 27 } 28 } 29 return a; 30 } 31 32 public static void main(String[] args) { 33 Scanner reader=new Scanner(System.in); 34 int col=reader.nextInt(); 35 int[] a=printYangHui(col); 36 int f=1; 37 int count=0; 38 int cp=col; 39 for(int i=1;i<=col;i++){ 40 for(int k=1;k<=cp;k++){ 41 System.out.print(" "); 42 } 43 cp--; 44 count++; 45 int flag=(i)*(i-1)/2; 46 for(int j=1;j<=count;j++){ 47 System.out.print(" "+a[flag+j]); 48 } 49 System.out.println(); 50 } 51 52 53 54 } 55 56 }
2.输出结果:

实验心得:
熟悉了Scanner输入语句对一维数组赋值的使用

浙公网安备 33010602011771号