杨辉三角输出

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");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值