复制代码 代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,k;
int line;
int *prev, *next;
printf("输入要查看杨辉三角的行数(大于2):");
scanf("%d",&line);
if(line < 2)
{
printf("行数小于2,Goodbye!\n");
exit(1);
}
for(i=1; i<=line; i++) //前两行的打印
printf(" ");
printf("%6d\n",1);
for(i=1; i<=line-1; i++)
printf(" ");
printf("%6d%6d\n",1,1);
prev = malloc(2*sizeof(int));
prev[0] = 1;
prev[1] = 1;
for(i=3; i<=line; i++) //从第三行开始打印
{
next = malloc(i*sizeof(int));
next[0] = 1;
next[i-1] = 1;
for(j=line; j>=i; j--) //外部空格
{
printf(" ");
}
printf("%6d",1);
for(k=2; k<i; k++) //数字
{
next[k-1] = prev[k-2] + prev[k-1];
printf("%6d",next[k-1]);
}
}
printf("%6d\n",1);
free(prev);
prev = next;
}
free(next);
return 0;
}