c++ setw的使用

来源:百度知道 编辑:UC知道 时间:2024/05/29 01:10:02
setw因该是限制限制宽度的啊,但为什么我将程序中swetw(5) 改成 1 仍旧输出 50?

#include<iomanip>
#include<iostream>
using namespace std;
void main()
{int i,j,k;
i=100;
j=50;
float x,y;
x=-0.7;
y=8.123456;
k=i-j;
cout<<setw(5)<<k<<'\n';
cout<<"k="<<k<<'\n';
cout<<setprecision(4)<<y<<'\n';
cout<<"y="<<y<<endl;
cout<<"x+y="<<x+y<<endl;
cout<<setprecision(0)<<x+y<<endl;}

分别把宽度设为2,3,4,结果如下
50
k=50
8.123
y=8.123
x+y=7.423
7.42346
Press any key to continue

50
k=50
8.123
y=8.123
x+y=7.423
7.42346
Press any key to continue
50
k=50
8.123
y=8.123
x+y=7.423
7.42346
Press any key to continue

注意看第一行与第二行,当宽度设为1的时候,已没有空格了,但结果还要输出,因此得到的不是5,而是50。