How to simplify fractions in C#?

前端 未结 5 2376
暗喜
暗喜 2020-12-11 17:55

I\'m looking for a library or existing code to simplify fractions.

Does anyone have anything at hand or any links?

P.S. I already understand the process but r

5条回答
  •  暖寄归人
    2020-12-11 18:16

    A custom solution:

    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;
                }
            }
        }
    }
    

    Example usage:

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

    Outupts:

    2
    3
    5
    

    By the way, this is my first c# program. Thought it would simply be a fun problem to try a new language with, and now I'm in love! It's like Java, but everything I wish was a bit different is exactly how I wanted it

    <3 c#


    Edit: Btw don't forget to make it static void if it's for your Main class.

提交回复
热议问题