在 C++ 中用 cout 列印正確的小數點位數


本文將介紹如何按一些預定義的小數位數列印某些浮點數。在 C++ 中,我們可以使用帶有 cout 的 setprecision 來實現此操作。它出現在 C++ 的 iomanip 標頭檔案中。

示例程式碼

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
   double x = 2.3654789d;
   cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl;
   cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl;
   cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl;
}

輸出

Print up to 3 decimal places: 2.365
Print up to 2 decimal places: 2.37
Print up to 7 decimal places: 2.3654789

更新於: 30-Jul-2019

14K+ 瀏覽

啟動你的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.