-
Notifications
You must be signed in to change notification settings - Fork 409
/
打印杨辉三角.c
45 lines (40 loc) · 2.47 KB
/
打印杨辉三角.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//杨辉三角是我们从初中就知道的,现在,让我们用C语言将它在计算机上显示出来。
//在初中,我们就知道,杨辉三角的两个腰边的数都是1,其它位置的数都是上顶上两个数之和。这就是我们用C语言写杨辉三角的关键之一。在高中的时候我们又知道,杨辉三角的任意一行都是的二项式系数,n为行数减1。也就是说任何一个数等于这个是高中的组合数。n代表行数减1,不代表列数减1。如:第五行的第三个数就为=6。
//现在我们按第一种思路来写:先定义一个二维数组:a[N][N],略大于要打印的行数。再令两边的数为1,即当每行的第一个数和最后一个数为1。a[i][0]=a[i][i-1]=1,n为行数。除两边的数外,任何一个数为上两顶数之和,即a[i][j]=a[i-1][j-1]+a[i-1][j]。最后输出杨辉三角。代码如下:
#include <stdio.h>
#define N 14
void main()
{
int i, j, k, n=0, a[N][N]; /*定义二维数组a[14][14]*/
while(n<=0||n>=13){ /*控制打印的行数不要太大,过大会造成显示不规范*/
printf("请输入要打印的行数:");
scanf("%d",&n);
}
printf("%d行杨辉三角如下:\n",n);
for(i=1;i<=n;i++)
a[i][1] = a[i][i] = 1; /*两边的数令它为1,因为现在循环从1开始,就认为a[i][1]为第一个数*/
for(i=3;i<=n;i++)
for(j=2;j<=i-1;j++)
a[i][j]=a[i-1][j-1]+a[i-1][j]; /*除两边的数外都等于上两顶数之和*/
for(i=1;i<=n;i++){
for(k=1;k<=n-i;k++)
printf(" "); /*这一行主要是在输出数之前打上空格占位,让输出的数更美观*/
for(j=1;j<=i;j++) /*j<=i的原因是不输出其它的数,只输出我们想要的数*/
printf("%6d",a[i][j]);
printf("\n"); /*当一行输出完以后换行继续下一行的输出*/
}
printf("\n");
}
//运行结果:
//请输入要打印的行数: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