代码之家  ›  专栏  ›  技术社区  ›  Andrew Harry

如何简化C中的分数?

  •  5
  • Andrew Harry  · 技术社区  · 16 年前

    我正在寻找一个库或现有的代码来简化分数。

    有人手头有什么东西或者有什么链接吗?

    P.S.I已经 understand the process 但真的不想重写轮子

    更新

    好的,我已经检查了 fraction library on the CodeProject 但我有一个比简化分数更棘手的问题。

    我必须减少 百分比分割 可以是20%/50%/30%(始终等于100%)。

    5 回复  |  直到 15 年前
        1
  •  11
  •   Gabe Timothy Khouri    16 年前

    我想你只需要除以所有数字的gcd。

    void Simplify(int[] numbers)
    {
        int gcd = GCD(numbers);
        for (int i = 0; i < numbers.Length; i++)
            numbers[i] /= gcd;
    }
    int GCD(int a, int b)
    {
        while (b > 0)
        {
            int rem = a % b;
            a = b;
            b = rem;
        }
        return a;
    }
    int GCD(int[] args)
    {
        // using LINQ:
        return args.Aggregate((gcd, arg) => GCD(gcd, arg));
    }
    

    我没有尝试过这个代码,但它看起来很简单,很正确(假设您的数字都是正整数,并且不传递空数组)。

        2
  •  3
  •   Matthew Flaschen    16 年前

    您可以使用免费的microsoft.fsharp.math.bigratical F# Power Pack 图书馆。虽然它取决于F(这是免费的,包含在VS2010中),但它可以从C使用。

    BigRational reduced = BigRational.FromInt(4)/BigRational.FromInt(6);
    Console.WriteLine(reduced);
        2/3
    Console.WriteLine(reduced.Numerator);
        2
    Console.WriteLine(reduced.Denominator);
        3
    
        3
  •  2
  •   Cam    16 年前

    自定义解决方案:

    void simplify(int[] numbers)
    {
        for (int divideBy = 50; divideBy > 0; divideBy--)
        {
            bool divisible = true;
            foreach (int cur in numbers)
            {   
    
                //check for divisibility
                if ((int)(cur/divideBy)*divideBy!=cur){
                    divisible = false;
                    break;
                }
    
            }
            if (divisible)
            {
                for (int i = 0; i < numbers.GetLength(0);i++ )
                {
                    numbers[i] /= divideBy;
                }
            }
        }
    }
    

    示例用法:

    int [] percentages = {20,30,50};
    simplify(percentages);
    foreach (int p in percentages)
    {
        Console.WriteLine(p);
    }
    

    Outupts:

    2
    3
    5
    

    顺便说一下,这是我的第一个C程序。我以为用一种新语言来尝试只是个有趣的问题,现在我爱上了!它就像Java,但我希望的东西有点不同,正是我想要的。

    <3℃


    编辑:顺便说一句,如果它是为你的主类设计的,不要忘记使它成为静态的无效。

        4
  •  1
  •   MiffTheFox    16 年前

    This library 看起来这可能是你需要的:

    var f = new Fraction(numerator, denominator);
    numerator = f.Numerator;
    denominator = f.Denominator;
    

    虽然,我还没有测试过它,所以看起来你可能需要和它一起玩才能让它工作。

        5
  •  1
  •   duffymo    16 年前

    我所看到的分数的最好例子是 Timothy Budd's "Classic Data Structures in C++" . 他的执行情况很好。它包括一个简单的GCD算法的实现。

    适应C并不难。