一、C++ 輸入與輸出 格式化輸出
1.cin與cout
2.格式化輸出
2.1設置域寬及位數(shù)
對于實型,cout 默認輸出六位有效數(shù)據(jù),setprecision(2) 可以設置有效位數(shù),setprecision(n)<<setiosflags(ios::fixed)合用,可以設置小數(shù)點右邊的位數(shù)。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream> #include <iomanip> using namespace std; int main() { printf ( "%c\n%d\n%f\n" , 'a' ,100,120.00); printf ( "%5c\n%5d\n%6.2f\n" , 'a' ,100,120.00); cout <<setw(5)<< 'a' <<endl <<setw(5)<<100<<endl <<setprecision(2)<<setiosflags(ios::fixed)<<120.00<<endl; return 0; } |
2.2按進制輸出
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream> #include <iomanip> using namespace std; int main() { int i = 123; cout<<i<<endl; cout<<dec<<i<<endl; cout<<hex<<i<<endl; cout<<oct<<i<<endl; cout<<setbase(16)<<i<<endl; return 0; } |
2.3設置填充符
可以設置域寬的同時,設置左右對齊及填充字符。
1
2
3
4
5
6
7
8
9
10
11
|
#include <iostream> #include <iomanip> using namespace std; int main() { cout<<setw(10)<<1234<<endl; cout<<setw(10)<<setfill( '0' )<<1234<<endl; cout<<setw(10)<<setfill( '0' )<<setiosflags(ios::left)<<1234<<endl; cout<<setw(10)<<setfill( '-' )<<setiosflags(ios::right)<<1234<<endl; return 0; } |
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!
原文鏈接:https://blog.csdn.net/qq_43414070/article/details/120988455