c++ - 如何在C++中用N个小数来字符串化分数

标签 c++ string math c++17 base

我想以可变精度将C++中的无符号整数的一部分字符串化。因此,1/3将使用0.33precision打印为2。我知道floatstd::ostream::precision可用于快速而肮脏的解决方案:

std::string stringifyFraction(unsigned numerator,
                              unsigned denominator,
                              unsigned precision)
{
    std::stringstream output;
    output.precision(precision);
    output << static_cast<float>(numerator) / denominator;
    return output.str();
}
但是,这还不够好,因为float的精度有限,并且实际上无法准确表示十进制数字。我还有什么其他选择?如果我想要100位左右,或者出现小数,即使double也会失败。

最佳答案

始终可以执行长除法以逐位数字化字符串。注意结果由整数部分和小数部分组成。我们可以简单地使用/运算符进行除法并调用std::to_string来获得不可或缺的部分。对于其余部分,我们需要以下功能:

#include <string>

std::string stringifyFraction(const unsigned num,
                              const unsigned den,
                              const unsigned precision)
{
    constexpr unsigned base = 10;

    // prevent division by zero if necessary
    if (den == 0) {
        return "inf";
    }

    // integral part can be computed using regular division
    std::string result = std::to_string(num / den);
    
    // perform first step of long division
    // also cancel early if there is no fractional part
    unsigned tmp = num % den;
    if (tmp == 0 || precision == 0) {
        return result;
    }

    // reserve characters to avoid unnecessary re-allocation
    result.reserve(result.size() + precision + 1);

    // fractional part can be computed using long divison
    result += '.';
    for (size_t i = 0; i < precision; ++i) {
        tmp *= base;
        char nextDigit = '0' + static_cast<char>(tmp / den);
        result.push_back(nextDigit);
        tmp %= den;
    }

    return result;
}
您只需将base用作模板参数,就可以轻松地将其扩展为与其他库一起使用,但是您就不能再使用std::to_string了。

关于c++ - 如何在C++中用N个小数来字符串化分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63511627/

相关文章:

c++ - static const int 作为 map 下标

c++ - 在 C++ 中以编程方式从 DLL 中获取 DLL 版本 - 再次

c - 字符数组应该如何用作字符串?

java - 将 JSONObject 格式化为 JSONArray

python - python中的负战俘

c++ - C/C++ 将二进制数据映射到结构成员

c++ - 将派生类实例作为 void* 传递给 C++ 中的通用回调

java - 生成字典序最大的字符串

java - 用高效的加入和满足操作来代表反链

python - 计算高斯分布的标准差