输出一个杨辉三角还比较简单,让我们把这个杨辉三角对齐好
注释写的比较多,应该不需要解释了。
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int t(int n)//算出一个数有多少位,进而控制空格数
{
int a=0;
while(n>=1)
{
n=n/10;
a++;
}
return a;
}
int main()
{
int line;//总共有几行的数字
int i,j,k,l;
int b;
int c;//This is the digits of each number.
scanf("%d",&line);
int q[100][100];
q[0][0]=1;
for(i=1;i<line;i++)//用i来遍历行数,i should start from line2,since there is only one number in the line 1
{
q[i][0]=1;//give the important condition that the first number of each line is 1
q[i][i]=1;//let the last number of each line to be 1
for (j=1;j<=i;j++)//j starts from the second number of each line
{
q[i+1][j]=q[i][j-1]+q[i][j];//add the two numbers above the number together
}
}
b=t(q[line-1][(int)(line/2)]);//This is the digits of the biggest number in the triangle.
for(i=0;i<line;i++)
{
for(k=0;k<(line-i);k++)
{
for(l=0;l<b;l++) printf(" ");//b*(line-i) spaces should be in the front of each line
}
for(j=0;j<=i;j++)
{
c=t(q[i][j]);//count the digits of each number
for (k=0;k<b-c;k++) printf(" ");//complete the space for each number,fill it with b-c spaces
for(k=0;k<b;k++)printf(" ");//give intervals for every two numbers
printf("%d",q[i][j]);
}
printf("\n");
}
return 0;
}