一、setw函數
在介紹setprecision函數前,我們先來了解一下setw函數。
setw函數的作用是設置輸出流中下一個輸出值所佔的寬度,若輸出值的數據位數小於設置的寬度,則用空格字符進行左對齊或右對齊操作。
#include <iomanip> #include <iostream> using namespace std; int main() { cout << setw(10) << 123 << endl; cout << setw(10) << "Hallo" << endl; return 0; }
上述代碼的輸出結果為:
123 Hallo
二、setprecision函數
setprecision函數的作用是設置數字浮點輸出的精度。
通過控制輸出流格式控制控制,讓輸出數據精度達到要求。
setprecision函數可以精確到小數點後面多少位。
#include <iomanip> #include <iostream> using namespace std; int main() { double d1 = 1.234, d2 = 1.235, d3 = 1.236; cout << setprecision(1) << d1 << endl; cout << setprecision(2) << d2 << endl; cout << setprecision(3) << d3 << endl; return 0; }
上述代碼的輸出結果為:
1.2 1.24 1.236
三、setiosflags函數
setiosflags函數可以設置輸出流的一些狀態標誌。
在使用setiosflags函數時,需要在頭文件iomanip中引入setiosflags頭文件。
如下:
#include<iomanip> //頭文件iomanip中提供的函數之一
setiosflags函數有許多參數,常見的有:
- ios::left:向左對齊
- ios::right:向右對齊
- ios::showpoint:顯示小數點
- ios::showpos:顯示正負號
#include <iomanip> #include <iostream> using namespace std; int main() { double d = 12.3456; cout << setiosflags(ios::left) << setiosflags(ios::showpoint) << setiosflags(ios::showpos) << setiosflags(ios::fixed) << setprecision(3) << d << endl; return 0; }
上述代碼的輸出結果為:
+12.346
四、setbase函數
setbase函數用於設置流使用的輸出進制,可以使用16進制、10進制和8進制
#include <iomanip> #include <iostream> using namespace std; int main() { int num = 7; cout << setbase(10) << num << endl; //十進制 cout << setbase(8) << num << endl; //八進制 cout << setbase(16) << num << endl; //十六進制 return 0; }
上述代碼的輸出結果為:
7 7 7
五、setfill函數
setfill函數用於設置填充字符,可以是空格、0或其他字符。
如下:
#include <iomanip> //頭文件iomanip中提供的函數之一
#include <iomanip> #include <iostream> using namespace std; int main() { int num = 7; cout << setiosflags(ios::left) << setfill('*') << setw(10) << num << endl; cout << setiosflags(ios::right) << setfill('#') << setw(10) << num << endl;//右對齊 return 0; }
上述代碼的輸出結果為:
7******** ########7
六、相關函數的綜合使用
結合以上函數,可以實現各種複雜的格式控制與輸出。
#include <iomanip> #include <iostream> using namespace std; int main() { double d1 = 12341.2312, d2 = 23.1234, d3 = 123143.1234; cout << setiosflags(ios::left) << setfill('*') << setw(15) << setprecision(2) << d1 << endl; cout << setiosflags(ios::right) << setfill('0') << setiosflags(ios::showpoint) << setw(10) << setprecision(3) << d2 << endl; cout << setiosflags(ios::left) << setfill('.') << setw(15) << setprecision(3) << d3 << endl; return 0; }
上述代碼的輸出結果為:
12341.23******* 000023.123 123143.123......
七、總結
以上就是setprecision函數的相關介紹,結合其他相關函數的使用可以靈活地控制輸出格式和數據精度。
原創文章,作者:KBUMP,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/369733.html