C++ 如何计算带有 n 个小数位的浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14677448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:35:11  来源:igfitidea点击:

How to cout a float number with n decimal places

c++formattingcout

提问by Muhammad Barrima

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

可能的重复:
如何使用 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" ?!

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

回答by Jesse Good

You need std::fixedand std::setprecision:

你需要std::fixedstd::setprecision

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

These require following header:

这些需要以下标题:

#include <iomanip>

回答by Muhammad Barrima

Try setprecision:

尝试setprecision

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