c++ - 在 C++ 中的字符串函数的返回语句中设置精度内联
问题描述
我有一个返回字符串的函数,我想在返回行中设置我的数字的精度。我知道这可以使用 cout 来完成,但我似乎无法在 return 语句中实现这一点。
例如:
std::string dividePrecision2(float a, float b)
{
float temp = a / b;
return "Your result with a precision of 2 is " + std::to_string(temp) + '\n';
}
如果我要这样创建一个字符串:
std::string str = dividePrecision2(10.0f, 3.0f);
该字符串的值为 3.33。
解决方案
由于反馈,我得出的解决方案如下:
std::string dividePrecision2(float a, float b)
{
float temp = a / b;
std::stringstream result;
result.precision(2);
result << std::fixed << "Your result with a precision of 2 is " << temp + '\n';
return result.str();
}
此外,如果您有多个精度,则可以在流中设置精度:
result << std::fixed << "x has a precision of 2" << std::setprecision(2) << x << " and y has a precision of 6" << std::setprecision(6) << y << '\n';
推荐阅读
- android - 移动应用(android/ios)中按钮点击的全局事件监听器
- vb.net - 注册用VB.NET制作的com dll
- python - Word Mover 距离与 SpaCy 的非归一化结果
- python - 如何在列表中使用 HH:MM 格式的正则表达式过滤器获取唯一出现值的输出?
- angular - IONIC 4:无法读取未定义的属性“获取”
- r - data.table 中的“递归”自联接
- javascript - 两个几乎相同的 javascript;一个有效,另一个无效
- reactjs - 如何使用 Auth0 和 React 前端保护 S3 存储桶中的图像
- tensorflow - 如何在 keras 中实现这种损失
- reactjs - 模块解析失败:使用 webpack 构建反应时出现意外令牌 (6:16)