Calculate a Ratio in C#

前端 未结 5 1982
半阙折子戏
半阙折子戏 2020-12-03 05:36

I thought this would be simple, but searching Google didn\'t seem to help.

I\'m basically trying to write a function which will return a ratio as a string (eg 4:3) w

5条回答
  •  难免孤独
    2020-12-03 05:37

    Are you basically trying to get the greatest common denominator - GCD for the two numbers and then dividing them by that and thus getting your string ?

    I.e: 800 : 600 ; the greatest common denominator = 200 thus 4:3.

    This would be able to deal with all integer numbers. Sorry for not sending the code, but I think that from this on it should be simple enough.

    public int GCD(int a, int b)
    
    {
        while (a != 0 && b != 0)
        {
             if (a > b)
                a %= b;
             else
                b %= a;
        }
         if (a == 0)
             return b;
         else
             return a;
    }
    
    // Using Konrad's code: 
    
    var gcd = GCD(A, B);
    return string.Format("{0}:{1}", A / gcd, B / gcd)
    

提交回复
热议问题