要求:打印10行杨辉三角形
提示:
杨辉三角是一个由数字排列成的三角形数表,一般形式如下:
1 n=0
1 1 n=1
1 2 1 n=2
1 3 3 1 n=3
1 4 6 4 1 n=4
1 5 10 10 5 1 n=5
1 6 15 20 15 6 1 n=6
...
此数列中各行中的数字正好是二项式a+b乘方后,展开始终各项的系数。如:
(a+b)^1=a^1+b^1
(a+b)^2=a^2+2ab+b^2
(a+b)^3=a^3+3a^2b+3ab^2+b^3
...
(a+b)^6=a^6+6a^5b+15a^4b^2+20a^3b^3+15a^2b^4+6ab^5+b^6(注意发现规律)
...
打印出来,形如:
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
...
答案:
#include <stdio.h> int c(int x, int y) { int z; if(y==1 || y==x+1) return 1; // 如果是x行的第1列或第x+1列,则为1 z = c(x - 1, y - 1) + c(x - 1, y); return z; } int main() { int i, j,n=13; printf("N="); while(n>12) scanf("%d", &n); for(i = 0; i <= n; i++) { for(j = 0; j < 24- 2 * i; j++) printf(" "); // 输入第i行前的空格 for(j = 1; j < i + 2; j++) printf("%4d", c(i, j)); printf("\n"); } }
输出: