gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:47:56 25 4
gpt4 key购买 nike

我想以可变精度将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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com