一些题目会涉及到场宽的问题,例如打印杨辉三角形。
下面是一个比较:
#include<bits/stdc++.h>
using namespace std;
int main(){
int a=45;
cout<<setw(4)<<a<<endl;
printf("%4d\n",a);
}
结果如下:
45
45
--------------------------------
Process exited after 0.09044 seconds with return value 0
请按任意键继续. . .
【题目】打印杨辉三角形的前10行。杨辉三角形如下:
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
很明显,通过数数,场宽是6。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int a[11][11];
int main(){
int n=10;
a[1][1]=1;
for(int i=2;i<=n;++i){
a[i][1]=1;a[i][i]=1;
for(int j=2;j<=i-1;++j){a[i][j]=a[i-1][j-1]+a[i-1][j];}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=3*(n-i);j++){cout<<" ";}
for(int k=1;k<=i;k++){cout<<setw(6)<<a[i][k];}//printf("%6d",a[i][k]);场宽
cout<<endl;
}
}