数组法和公式法
View Code
1 //杨辉三角 2 /* 3 5 4 5 1 6 1 1 7 1 2 1 8 1 3 3 1 9 1 4 6 4 1 10 11 */ 12 //方法一:数组法 13 #include<stdio.h> 14 int main() 15 { 16 int i,j,a[32][32],n; 17 for(i=1;i<32;i++)//将第一列以及对角线上的元素置1 18 { 19 a[i][1]=1; 20 a[i][i]=1; 21 } 22 for(i=2;i<32;i++) 23 { 24 for(j=2;j<i;j++) 25 a[i][j]=a[i-1][j]+a[i-1][j-1]; 26 } 27 scanf("%d",&n); 28 for(i=1;i<=n;i++) 29 { 30 for(j=1;j<=i;j++) 31 printf("%d ",a[i][j]); 32 printf("\n"); 33 } 34 return 0; 35 } 36 //方法二:公式法 37 #include<stdio.h> 38 int main() 39 { 40 int n,i,j,t; 41 scanf("%d",&n); 42 t=1; 43 for(i=1;i<=n;i++) 44 { 45 t=1; 46 printf("1 "); 47 for(j=1;j<i;j++) 48 { 49 t=t*(i-j)/j; 50 printf("%d ",t); 51 } 52 printf("\n"); 53 } 54 return 0; 55 }