随笔 - 164  文章 - 0  评论 - 4  阅读 - 9768

C++输入输出

c语言的printf()请自行回顾
头文件:#include<iomanip> 用于C++格式化输出

摘记

控制符 作用 作用范围
set(w) 设置字段宽度为n位 后面紧跟一个输出
setfill(c) 设置字符填充,c可以是字符常或字符变量 设置以后
setprecision(n) 设置浮点数的有效数字为n位 设置以后
setiosflags(ios::left) 或left 输出左对齐 设置之后
setiosflags(ios::right) 输出右对齐 设置之后

注:
默认靠右输出
fixed与setprecision()连用可以设置小数点后面的小数个数
cout<<fixed<<setprecision(10)<<p<<'\n';

setbase(n)
设置整数为n进制(n=8,10,16)
setiosflags(ios::fixed)
设置浮点数以固定的小数位数显示
setiosflags(ios::scientific)
设置浮点数以科学计数法表示
setiosflags(ios::skipws)
忽略前导空格
代码展示:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a=3.141592654,b=1.123456789,c=5.256486424564864;
cout<<a<<' '<<b<<' '<<c<<"#\n";
cout<<setw(10)<<a<<' '<<b<<"#\n";
cout<<setiosflags(ios::left)<<setw(10)<<a<<' '<<setw(10)<<b<<"#\n";
cout<<setfill('*');
cout<<setw(10)<<a<<' '<<setw(10)<<b<<"#\n";
cout<<right<<setw(10)<<a<<' '<<setw(10)<<b<<"#\n";
cout<<fixed<<setprecision(4)<<a<<' '<<b<<' '<<c<<"#\n";
cout<<a<<' '<<b<<' '<<c<<"#\n";
return 0 ;
}

结果:
image

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double PI=3.141592654;
cout<<PI<<endl;
cout<<setprecision(2)<<PI<<endl;
cout<<fixed<<setprecision(2)<<PI<<endl;//这里多了个fixed!!!
cout<<setfill('*')<<setw(20)<<setprecision(10)<<PI<<endl;
cout<<setfill('*')<<setw(20)<<setprecision(10)<<left<<PI<<endl;
cout<<scientific<<setprecision(10)<<PI<<endl;
cout<<scientific<<uppercase<<setprecision(10)<<PI<<endl;
return 0 ;
}
// 输出结果如下:
// 3.14159
// 3.1
// 3.14
// ********3.1415926540
// 3.1415926540********
// 3.1415926540e+000
// 3.1415926540E+000

快读快写

template<typename T>inline void read(T &x) {
int f = 1;
x = 0;
char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) if(ch == '-') f = -1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48);
x *= f;
}
template<typename T>
void print(T x){
if (!x) return ;
if (x < 0) putchar('-'),x = -x;
print(x / 10);
putchar(x % 10 + '0');
}

相关资料

https://cplusplus.com/
https://blog.csdn.net/gyxx1998/article/details/103337790 指定输出小数位数

posted on   Qiansui  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示