如何在 C++ 中使用 setprecision
-
使用
setprecision()方法為浮點數設定自定義精度 -
使用
setprecision()和std::fixed()為浮點數設定自定義精度 -
使用
setprecision()和std::fixed()將浮點數對齊到小數點
本文將演示關於如何在 C++ 中使用 setprecision 方法的多種方法。
使用 setprecision() 方法為浮點數設定自定義精度
setprecision() 是輸入/輸出操縱器庫 <iomanip> 的一部分,可以用來修改浮點數的預設精度。setprecision() 通常用於帶 I/O 流的表示式中。
下面的例子顯示瞭如何為 cout 輸出流物件設定浮點數精度。注意,setprecision() 適用於整數(整數部分和分數部分),並且當數字的大小大於指定的精度時會採用科學計數法。
#include <iomanip>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::fixed;
using std::setprecision;
using std::vector;
int main() {
vector<double> d_vec = {123.231, 2.2343, 0.324, 0.012,
26.9491092019, 11013, 92.001112, 0.000000234};
for (auto &i : d_vec) {
cout << setprecision(3) << i << " | ";
}
cout << endl;
return EXIT_SUCCESS;
}
輸出:
123 | 2.23 | 0.324 | 0.012 | 26.9 | 1.1e+04 | 92 | 2.34e-07 |
使用 setprecision() 和 std::fixed() 為浮點數設定自定義精度
另外,我們還可以使用 setprecision() 和 fixed() 流操作器聯合列印小數點後相同位數的浮點數。fixed() 方法將數字的小數部分設定為固定長度,預設為 6 位。在下面的程式碼示例中,我們輸出到 cout 流,並在將數字插入到輸出中之前呼叫兩個操作器。
#include <iomanip>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::fixed;
using std::setprecision;
using std::vector;
int main() {
vector<double> d_vec = {123.231, 2.2343, 0.324, 0.012,
26.9491092019, 11013, 92.001112, 0.000000234};
for (auto &i : d_vec) {
cout << fixed << setprecision(3) << i << " | ";
}
cout << endl;
return EXIT_SUCCESS;
}
輸出:
123.231 | 2.234 | 0.324 | 0.012 | 26.949 | 11013.000 | 92.001 | 0.000 |
使用 setprecision() 和 std::fixed() 將浮點數對齊到小數點
最後,我們可以結合 setw、right、setfill、fixed 和 setprecision 操作器來輸出向小數點對齊的浮點數。setw 方法以傳遞的字元數為引數指定輸出流寬度。setfill 方法設定一個字元,將未使用的空格填滿,right 方法告訴 cout 填充操作適用的一側。
#include <iomanip>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::fixed;
using std::setprecision;
using std::vector;
int main() {
vector<double> d_vec = {123.231, 2.2343, 0.324, 0.012,
26.9491092019, 11013, 92.001112, 0.000000234};
for (auto &i : d_vec) {
cout << std::setw(10) << std::right << std::setfill(' ') << fixed
<< setprecision(4) << i << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
輸出:
123.2310
2.2343
0.3240
0.0120
26.9491
11013.0000
92.0011
0.0000
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
