我有一个返回字符串的函数,我想在返回行中设置数字的精度。我知道这可以使用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';