首页 > 解决方案 > 在 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。

标签: c++stringprecision

解决方案


由于反馈,我得出的解决方案如下:

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';

推荐阅读