How to cout a float number with n decimal places [duplicate]

不羁的心 提交于 2019-11-26 14:29:03

问题


Possible Duplicate:
How do I print a double value with full precision using cout?

float a = 175.;
   cout << a;

If I run the previous code I'll get just 175, how can I cout the number with (for example) 3 decimal places even they were zeros .. How can I print "175.000" ?!


回答1:


You need std::fixed and std::setprecision:

 std::cout << std::fixed << std::setprecision(3) << a;

These require following header:

#include <iomanip>



回答2:


Try setprecision:

cout.setf(ios::fixed);
cout << setprecision(3) << a << endl;


来源:https://stackoverflow.com/questions/14677448/how-to-cout-a-float-number-with-n-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!