如何在 C 中使用 setprecision

新手上路,请多包涵

我是 C++ 的新手,我只想输出最多 2 位的点数。 just like if number is 3.444 , then the output should be 3.44 or if number is 99999.4234 then output should be 99999.42 , How can我这样做。价值是动态的。这是我的代码。

 #include <iomanip.h>
#include <iomanip>
int main()
{
    double num1 = 3.12345678;
    cout << fixed << showpoint;
    cout << setprecision(2);
    cout << num1 << endl;
}

但它给了我一个错误,未定义的固定符号。

原文由 Malik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 533
1 个回答

这是适用于任何精度设置的解决方案。为了在 sstream 中精确到小数点后 2 位,这是我的代码片段。示例 3.444 为 3.44,1.10 为 1.10,1.3245 为 1.32

 #include<sstream>

std::wostringtream stream;
float value = 3.14159;
// To get the output to 2 decimal places
stream.precision(2);
stream << std::fixed << value;
std::wcout<<stream.str()<<L"\n";

// The output will be 3.14

原文由 AnuragD 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题