算法简化小数分数小数、算法、分数

2023-09-02 11:47:07 作者:对温柔懂得不多。

我试着写一个算法,以简化小数的一小部分,并意识到这不是太简单了。令人惊讶的看着我在网上和所有的C $ CS $我发现无论是在哪里过久,否则也不会在某些情况下工作。什么是更讨厌的是,他们并没有对循环小数的工作。我在想,但是否会有一个数学家/程序员在这里谁理解所有涉及的流程简化小数的一小部分。有人吗?

I tried writing an algorithm to simplify a decimal to a fraction and realized it wasn't too simple. Surprisingly I looked online and all the codes I found where either too long, or wouldn't work in some cases. What was even more annoying was that they didn't work for recurring decimals. I was wondering however whether there would be a mathematician/programmer here who understands all the involved processes in simplifying a decimal to a fraction. Anyone?

推荐答案

唉,看来我最后不得不做我自己。我不得不创建一个程序模拟自然的方式,我会解决它自己。我刚刚提交了code至$ C $的CProject为写出整个code,这里将不适合。你可以从这里下载该项目 Fraction_Conversion ,还是看的$ C $的CProject页面这里。

Well, seems I finally had to do it myself. I just had to create a program simulating the natural way I would solve it myself. I just submitted the code to codeproject as writing out the whole code here won't be suitable. You can download the project from here Fraction_Conversion, or look at the codeproject page here.

下面是它如何工作的:

找到了给定的小数是负数 十进制转换为绝对值 在获取给定的十进制整数部分 获取小数部分 检查小数点是否再次发生。若小数点为经常性,我们再返回准确循环小数 如果小数点是不是经常性,通过改变分子10 ^没有开始减少。小数,否则我们减去1,从分子 然后降低分数

code preVIEW:

Code Preview:

    private static string dec2frac(double dbl)
    {
        char neg = ' ';
        double dblDecimal = dbl;
        if (dblDecimal == (int) dblDecimal) return dblDecimal.ToString(); //return no if it's not a decimal
        if (dblDecimal < 0)
        {
            dblDecimal = Math.Abs(dblDecimal);
            neg = '-';
        }
        var whole = (int) Math.Truncate(dblDecimal);
        string decpart = dblDecimal.ToString().Replace(Math.Truncate(dblDecimal) + ".", "");
        double rN = Convert.ToDouble(decpart);
        double rD = Math.Pow(10, decpart.Length);

        string rd = recur(decpart);
        int rel = Convert.ToInt32(rd);
        if (rel != 0)
        {
            rN = rel;
            rD = (int) Math.Pow(10, rd.Length) - 1;
        }
        //just a few prime factors for testing purposes
        var primes = new[] {41, 43, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2};
        foreach (int i in primes) reduceNo(i, ref rD, ref rN);

        rN = rN + (whole*rD);
        return string.Format("{0}{1}/{2}", neg, rN, rD);
    }

感谢@大流士的给了我如何解决循环小数一个想法:)

Thanks @ Darius for given me an idea of how to solve the recurring decimals :)