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 @ 2023-04-05 17:10  Qiansui  阅读(72)  评论(0)    收藏  举报