C++和C语言的问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 19:54:35
有个问题 c语言中 %4d 在C++中 如何用cout命令实现??
王高手指教 本人小菜

#include <iostream>
#include <iomanip>//包含了格式控制的头文件
using namespace std;
int main()
{
double a=123.456,b=3.14159,c=-3214.67;
cout<<setiosflags(ios::fixed)<<setiosflags(ios::right)<<setprecision(2);
//这句是控制以下输出格式是:以right对齐,然后保留两位小数
cout<<setw(10)<<a<<endl;//字段宽度是10,相当于c里面的%d10
cout<<setw(10)<<b<<endl;
cout<<setw(10)<<c<<endl;
return 0;
}

...
cout.width(4);
cout << foo;
...

方法2:
#include <iomanip>

....

cout << setw(4) << foo;

设置精度:使用setprecision(精度)或cout.precision(精度)控制输出精度