C++ 在C+;中的字符串函数的返回语句中设置精度内联+;
我有一个返回字符串的函数,我想在返回行中设置数字的精度。我知道这可以用cout来实现,但我似乎不能在return语句中实现 例如:C++ 在C+;中的字符串函数的返回语句中设置精度内联+;,c++,string,precision,C++,String,Precision,我有一个返回字符串的函数,我想在返回行中设置数字的精度。我知道这可以用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 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();
}
std::字符串除法精度2(浮点a、浮点b)
{
浮动温度=a/b;
std::stringstream结果;
结果:精密度(2);
结果您可以使用stringstream
作为中介,接受流操纵器,如setprecision
。您还可以使用fmt
库,或者在C++20中使用std::format
。
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';