保留小数

  • 一般而言,c++中保留小数有两种做法。

cout

double ans=3.1415926;
cout<<setprecision(2)<<ans;

output
3.14

但需要注意的是,如果小数没有预设的那么长,其后面不会补零而是会改为空格。因此不太建议。
如果cout要四舍五入的话要加fixed

cout<<fixed<<std::setprecision(2)<<ans;

printf

double ans=3.1415926;
printf("%.2lf\n",ans);
prtinf("%.3lf\n",ans);
ans=3.14;
printf("%.5lf\n",ans);

output
3.14
3.142
3.14000

scanf会自动将不足的位补为0,同时自动四舍五入,拥有广泛的使用场景
但是在关闭输入输出流的时候不能使用,否则会导致输出混乱(即使你在本地是对的)

posted @ 2024-12-21 16:27  all_for_god  阅读(34)  评论(0)    收藏  举报