在这里,我们将看到如何打印一些浮点数直到一些预定义的小数位。在C ++中,我们可以将setprecision与cout一起使用来做这个词。它位于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