转发自某博客:http://blog.sina.com.cn/s/blog_6757fa030100o54z.html
C语言用法:
使用 setfill、setw 和 setprecision 操作器,这些操作器带有参数,并在头文件 iomanip.h 中定义。因此,此头文件必须包括在程序中。
#include<iostream.h>#include <iomanip.h>
#include<conio.h>
void main()
{
int amt1 = 100, amt2 = 12345;
float f1 = 10.0/3.0;
cout<<setfill('*');
cout<<"Amount 1:[";
cout<<setw(5)<<amt1<<"]\n";
cout<<"Amount 2:[";
cout<<setw(4)<<amt2<<"]\n";
cout<<"Default f1 = ["<<f1<<"]\n";
cout<<setprecision(2)<<"f1 = ["<<f1<<"]\n";
}
输出:
Amount 1:[**100]
Amount 2:[12345]
Default f1 = [3.33333]
f1 = [3.3]
您可看到,上面的输出与使用 width、fill 和 precision 操作器的程序的输出是相同的。
附:setw()设置域宽
就是你的输出要占多少个字符
比如:
cout<<setw(5)<<12345<<endl;
就输出
12345
cout<<setw(6)<<12345<<endl;
输出
空格+12345
要输出由字母B组成的菱形
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
for (int i=1;i<8;i++)
{
cout << setw(20-i) << setfill(' ') << " " << setw(2*i-1) << setfill('B') << "B"<< endl;
}
for (int i=8;i<14;i++)
{
cout << setw(i+6) << setfill(' ') << " " << setw(27-2*i) << setfill('B') << "B" << endl;
}
return 0;
}
另外:再挑战高难度点的,输出对角线的空心菱形(菱形的变长不能超过40),输入一个奇数值n,那么该菱形的高度为n。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
/*
for (int i=1;i<8;i++)
{
cout << setw(20-i) << setfill(' ') << " " << setw(2*i-1) << setfill('B') << "B"<< endl;
}
for (int i=8;i<14;i++)
{
cout << setw(i+6) << setfill(' ') << " " << setw(27-2*i) << setfill('B') << "B" << endl;
}
*/
int n;
cin >> n;
cout << setw(20) << setfill(' ') << " " << "B" << endl;
for (int i=1;i<=n-2;i++) //5,n-2
{
if (i==1)
{
cout << setw(20-i) << setfill(' ') << " " << "B" << setw(i*2-1) << setfill(' ') << "B" << "B" << endl;
}
else if(i<=(n-2)/2) //2,(n-2)/2
cout << setw(20-i) << setfill(' ') << " " << "B" << setw(i-1) << setfill(' ') << " " << "B" << setw(i-1) << setfill(' ') << " " << "B" << endl;
else if (i==((n-2)/2+1)) //3,(n-2)/2+1
cout << setw(20-i) << setfill(' ') << " " << "B" << setw(i*2-1) << setfill('B') << "B" << "B" << endl;
else if(i<=(n-3)) //4,(n-2)-1
cout << setw(i+21-n) << setfill(' ') << " " << "B" << setw(n-2-i) << setfill(' ') << " " << "B" << setw(n-2-i) << setfill(' ') << " " << "B" << endl;
else
{
cout << setw(i+21-n) << setfill(' ') << " " << "B" << "B" << "B" << endl;
}
}
/*
cout << setw(19) << setfill(' ') << " " << "B" << setw(1) << setfill(' ') << " " << "B" << endl;
cout << setw(18) << setfill(' ') << " " << "B" << setw(3) << setfill(' ') << " " << "B" << endl;
cout << setw(17) << setfill(' ') << " " << "B" << setw(5) << setfill(' ') << " " << "B" << endl;
cout << setw(18) << setfill(' ') << " " << "B" << setw(3) << setfill(' ') << " " << "B" << endl;
cout << setw(19) << setfill(' ') << " " << "B" << setw(1) << setfill(' ') << " " << "B" << endl;
*/
cout << setw(20) << setfill(' ') << " " << "B" << endl;
return 0;
}
输入和输出: