Calculate a Ratio in C#

前端 未结 5 1973
半阙折子戏
半阙折子戏 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:45

    You can simplify fractions by dividing numerator and denominator by their GCD:

    var gcd = GCD(A, B);
    return string.Format("{0}:{1}", A / gcd, B / gcd)
    

    And a very basic function for calculating the GCD, using the Euclidean algorithm:

    static int GCD(int a, int b) {
        return b == 0 ? Math.Abs(a) : GCD(b, a % b);
    }
    

提交回复
热议问题