如何在 C++ 中列印指定小數點的數字

Jinku Hu 2023年10月12日
如何在 C++ 中列印指定小數點的數字

本文將介紹如何在 C++ 中列印指定小數點的數字。

使用 std::fixedstd::setprecision 方法指定精度

本方法使用 <iomanip> 標頭檔案中定義的標準庫中的所謂 I/O 操作器(檢視完整列表)。這些函式可以修改流資料,主要用於 I/O 格式化操作。在第一個例子中,我們只使用 fixed 方法,它修改了預設的格式,使浮點數用定點符號寫入。注意,結果總是有一個預定義的小數點後 6 位精度。

#include <iomanip>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::fixed;
using std::vector;

int main() {
  vector<double> d_vec = {123.231,   2.2343,       0.324,
                          10.222424, 6.3491092019, 110.12329403024,
                          92.001112, 0.000000124};

  for (auto &d : d_vec) {
    cout << fixed << d << endl;
  }
  return EXIT_SUCCESS;
}

輸出:

123.231000
2.234300
0.324000
10.222424
6.349109
110.123294
92.001112
0.000000

另外,我們也可以將小數點固定在逗號之後,同時指定精度值。在下一個例子中,fixed 函式與 setprecision 函式一起呼叫,後者本身使用 int 值作為引數。

#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,
                          10.222424, 6.3491092019, 110.12329403024,
                          92.001112, 0.000000124};

  for (auto &d : d_vec) {
    cout << fixed << setprecision(3) << d << endl;
  }
  return EXIT_SUCCESS;
}

輸出:

123.231
2.234
0.324
10.222
6.349
110.123
92.001
0.000

前面的程式碼示例解決了最初的問題,但輸出的結果似乎很混雜,而且幾乎沒有可讀的格式。我們可以使用 std::setwstd::setfill 函式來顯示給定向量中的浮點數,並將其對齊到同一個逗號位置。為了達到這個目的,我們應該呼叫 setw 函式來告訴 cout 每個輸出的最大長度(本例中我們選擇 8)。接下來,呼叫 setfill 函式,指定一個 char 來填充填充位。最後,我們新增之前使用的方法(fixedsetprecision),並輸出到控制檯。

#include <iomanip>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::fixed;
using std::setfill;
using std::setprecision;
using std::setw;
using std::vector;

int main() {
  vector<double> d_vec = {123.231,   2.2343,       0.324,
                          10.222424, 6.3491092019, 110.12329403024,
                          92.001112, 0.000000124};

  for (auto &d : d_vec) {
    cout << setw(8) << setfill(' ') << fixed << setprecision(3) << d << endl;
  }
  return EXIT_SUCCESS;
}

輸出:

123.231
  2.234
  0.324
 10.222
  6.349
110.123
 92.001
  0.000
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ Float