如何cout一个带有n个小数位的浮点数[重复]

时间:2022-09-17 16:58:11

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

可能重复:如何使用cout以完全精度打印double值?

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" ?!

如果我运行前面的代码我将只得到175,我怎么能用(例如)3个小数位来输出数字,即使它们是零...我怎么能打印“175.000”?

2 个解决方案

#1


38  

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

你需要std :: fixed和std :: setprecision:

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

These require following header:

这些需要以下标题:

#include <iomanip>

#2


4  

Try setprecision:

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

#1


38  

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

你需要std :: fixed和std :: setprecision:

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

These require following header:

这些需要以下标题:

#include <iomanip>

#2


4  

Try setprecision:

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