C++ cout 如何保留小数输出

写了这么久的代码了,今天才发现自己不会用cout输出小数,真的感觉自己好傻。

cout<
​
​
#include 
#include 
#include 
using namespace std;
int main()
{
    double a = 12.2;
    printf("%.2lf\n", a);//不改变a的值
    cout << fixed << setprecision(2) << a << endl;//只需使用一次a值就会改变,后续不要再用
//用double时用加fixed再setprecision(), 
    cout << a << endl;
    float b = 2.236578;
    cout << setprecision(5) << b << endl;//setprecision()会自动四舍五入
//用float不用fixed
    cout << b << endl;

    return 0;
}

​

​

输出结果

12.20
12.20
12.20
2.23658
2.23658

读者可自行调试体会。

你可能感兴趣的:(c++,蓝桥杯,开发语言)