C++指定位数小数输出

关键词:头文件<iomanip>,指令setw(x),fixed,setprecision(x)。

setw()这个指令也可以配合setfill('')用于对齐输出,详情见另一篇博客https://www.cnblogs.com/ljy1227476113/p/9737334.html

例:输出4位小数

代码:

 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 int main()
 5 {
 6     double test[4] = { 1.1,1.12,1.123,1.1234 };
 7     for (int i = 0; i < 4; i++)
 8     {
 9         cout << fixed << setprecision(4) << test[i] << endl;
10     }
11 }

结果:

原文地址:https://www.cnblogs.com/ljy1227476113/p/9744518.html