问题描述
我想以可变精度将C ++中的一部分无符号整数字符串化.因此,使用2
的precision
将1/3
打印为0.33
.我知道float
和std::ostream::precision
可以用于快速而肮脏的解决方案:
I want to stringify a fraction of unsigned integers in C++ with variable precision. So 1/3
would be printed as 0.33
using a precision
of 2
. I know that float
and std::ostream::precision
could be used for a quick and dirty solution:
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
也会失败.
However, this is not good enough because float
has limited precision and can't actually represent decimal numbers accurately. What other options do I have? Even a double
would fail if I wanted 100 digits or so, or in case of a recurring fraction.
推荐答案
始终可以执行长除法以逐位数字化字符串.注意结果由整数部分和小数部分组成.我们可以通过使用/
运算符简单地除法并调用std::to_string
来获得不可或缺的部分.对于其余部分,我们需要以下功能:
It's always possible to just perform long division to stringify digit-by-digit. Note that the result consists of an integral part and a fractional part. We can get the integral part by simply dividing using the /
operator and calling std::to_string
. For the rest, we need the following function:
#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
了.
You could easily extend this to work with other bases as well, by just making base
a template parameter, but then you couldn't just use std::to_string
anymore.
这篇关于我如何在C ++中用N个小数字符串化分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!