如何计算具有 n 位小数的浮点数

How to cout a float number with n decimal places

本文关键字:小数 浮点数 何计算 计算      更新时间:2023-10-16

可能的重复项:
如何使用 cout 以全精度打印双精度值?

float a = 175.;
   cout << a;

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

你需要std::fixedstd::setprecision

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

这些需要以下标头:

#include <iomanip>

尝试setprecision

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