Ss 杨辉三角标准输出tips:(先提供思路,读者自己先试着完成)
1以行数约定输出的数目
2根据行数计算出可能出现的最大的字宽,而且每次输出的空格数目等于最大的字宽宽度,每个数字都要以同样的字宽输出,printf(“%3d”);
3编写组合数计算公式combi(int row, int col)
4当前要输出的数字根据其行列有combi计算出来,即C(row,col)
5每行输出的内容是先空格,再数字,行尾输出换行
6组合数的计算:利用迭代计算,C(N,K)àC(N,K+1); 起始C(N,0)=1;
接下来提供答案:
#include <stdio.h>
#include<iostream>
#define N 15
long combi(int n, int r){ //function to compute combinatorial numbers
int i;
long p = 1;
for (i = 1; i <= r; i++)
p = p * (n - i + 1) / i;
return p;
}
void main(int argv,char**argc) {
int n, r, t;
for (n = 0; n <= N; n++) { //there are N+1 rows in total
for (r = 0; r <= n; r++) { // there are n+1 numbers in number n row
int i; //the sequence of print is space first and then numbers
if (r == 0) { //print the spaces before the first number in every row
for (i = 0; i <= (N - n); i++)
printf(" "); //3 spaces is according to the width of longest numbers and every number should set the same width
}
else { //print space among numbers
printf(" ");
}
printf("%4d", combi(n, r)); //print numbers combi is used to compute combinatorial numbers according to its row and col.
}
printf("\n"); //line break/line feed
}
system("pause");
}