写了这么久的代码了,今天才发现自己不会用cout输出小数,真的感觉自己好傻。
cout<<setiosflags(ios::fixed)<<setprecision(2);//需要头文件#include <iomanip>
#include <iostream>
#include <cstdio>
#include <iomanip>
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++中如何使用cout精确地输出小数,包括设置精度和固定小数点位置。示例代码展示了如何使用`setiosflags(ios::fixed)`和`setprecision(2)`函数来控制浮点数的输出,并对比了`printf`和`cout`在处理浮点数时的不同。博主提醒读者注意`cout`输出小数后可能会影响变量的值。
2万+

被折叠的 条评论
为什么被折叠?



