c++ - 将浮点十进制值转换为分数

标签 c++ algorithm fractions

给定一个十进制浮点值,你如何找到它的小数当量/近似值?例如:

as_fraction(0.1) -> 1/10
as_fraction(0.333333) -> 1/3
as_fraction(514.0/37.0) -> 514/37

是否有通用算法可以将小数转换为小数形式?如何在 C++ 中简单高效地实现这一点?

最佳答案

先取小数部分再取gcd。使用欧氏算法 http://en.wikipedia.org/wiki/Euclidean_algorithm

void foo(double input)
{
    double integral = std::floor(input);
    double frac = input - integral;

    const long precision = 1000000000; // This is the accuracy.

    long gcd_ = gcd(round(frac * precision), precision);

    long denominator = precision / gcd_;
    long numerator = round(frac * precision) / gcd_;

    std::cout << integral << " + ";
    std::cout << numerator << " / " << denominator << std::endl;
}

long gcd(long a, long b)
{
    if (a == 0)
        return b;
    else if (b == 0)
        return a;

    if (a < b)
        return gcd(a, b % a);
    else
        return gcd(b, a % b);
}

关于c++ - 将浮点十进制值转换为分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643695/

相关文章:

c++ - 在 Linux 下使用连字符或下划线作为文件的单词分隔符

c++ - vector 的 vector 到一维数组

c++ - 使用 libharu 在 pdf 中打印日文字符

algorithm - 构建多边形的轮廓(特别是三角剖分)

C#多线程并发算法

algorithm - 算法的时间复杂度是多少?

html - 如何使用html写分数值?

c++ - 初学者对图像过滤的尝试

python - python的fractions.limit_denominator是怎么实现的?

f# - 如何在不损失精度的情况下在 F# 中表示分数?