以前只熟悉C語言的輸出格式,%d,%s,%f什麼的,c++的今天遇到了,記錄一下
先添加一個頭文件
#include <iomanip>
然後是一些格式控制了
setprecision 設置精度
float n = 133.4657864345;
cout << setprecision(8) << n << endl;
這樣輸出結果是 133.46578
也就是不帶小數點總共輸出8位
fixed 和setprecision配合可以設置小數部分位數
float n = 133.4657864345;
cout << fixed << setprecision(3) << n << endl;
這樣輸出結果是 133.466
也就是小數點後保留3位,四捨五入
setw 設置輸出寬度
setfill 設置填充
char a[] = "hello";
cout << setfill('q')<< setw(10) << a << endl;
輸出結果 qqqqqhello