2508 - 【数组】杨辉三角形(例题)
时间限制 : 1 秒
内存限制 : 128 MB
例5.11 打印杨辉三角形的前10行。杨辉三角形如下图:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
题目输入
无输入。
题目输出
杨辉三角形前10行,输出格式见样例输出(无需修改教材程序,体会setw()语句作用)。
输入/输出样例
输入格式
no input needed
输出格式
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
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
C++解答
#include<iomanip> #include<iostream> using namespace std; int main() { int a[20][21]; a[1][1]=1; for (int i=2; i<=10; ++i) { a[i][1]=1; a[i][i]=1; for (int j=2; j<=i-1; ++j) a[i][j]=a[i-1][j]+a[i-1][j-1]; } for (int i=1; i<11; i++) { if (i!=10) cout<<setw(30-3*i)<<" "; for (int j=1; j<=i; j++) cout<<setw(6)<<a[i][j]; cout<<endl; } return 0; }