c - 将小数转换为分数表达式的算法

标签 c haskell

假设我有一个像这样的小数

0.30000000000000027

知道用分数表示的相同数字的最佳算法是什么 所以给定某些 x 在 c 或 haskell 中找到满足 x=1/yy

我在想

 1/3> 0.30 >1/4

迭代左侧和右侧直到其中一个收敛并且 > 变为 = 所以第一次迭代看起来像

1/1  >  0.30000000000000027  > 1/somethinghere
1/2  >  0.30000000000000027  > 1/increase or decrease this 
1/3  >  0.30000000000000027 ...

我想澄清一下我可以轻松做到

0.30000000000000027  =  30000000000000027/  10^17

但是我想做

0.30000000000000027 = 1/x

在 c 或 haskell 中

最佳答案

瞧(几乎正确地转换为正常分数):

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

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

struct frac {
    int num;
    int denom;
};

struct frac to_frac(double x, int precision)
{
    int denom = 1;
    for (int i = 0; i < precision; i++) {
        denom *= 10;
    }

    int num = x * denom + 0.5; // hack: round if imprecise
    int gcdiv = gcd(num, denom);

    struct frac f;
    f.num = num / gcdiv;
    f.denom = denom / gcdiv;

    return f;
}

关于c - 将小数转换为分数表达式的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15847700/

相关文章:

haskell - 使用foldr和函数应用($)解释查找列表的第K个元素

haskell - 使用 Control.Lens 组合镜头,其中必须调用中间函数

c - 如何计算 C 文件中的行数?

c - Linux 中的依赖解析

c - 绘制溢出到顶级窗口之外的子窗口

haskell - 偏向 Monad 变压器

haskell - 在 Haskell 中解析命令行参数

haskell - 当我将其重写为 Foldl 时,为什么我的筛子不会终止?

c - "sizeof (char[0])"怎么用 GCC 编译得很好

如果该行包含空格,C 中的回车不能正常工作