Calculate a Ratio in C#

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

    With Using following 2 functions, you will be able tow get ratio of two numbers without using division operations.

    static int GCD(int p, int q)//find greatest common divisor
    {
        if (q == 0)
        {
            return p;
        }
    
        int r = p % q;
    
        return GCD(q, r);
    }
    static string  FindRatio(int num1, int num2)
    {
    
        string oran = "";
        int gcd;
        int quotient = 0;
        while (num1 >= num2)
        {
            num1 = num1 - num2;
            quotient++;
        }
    
        gcd = GCD(num1, num2);
    
        //without using division finding ration of num1 i1
        int i1 = 1;
        while (gcd*i1 != num1)
        {
            i1++;
        }
        //without using division finding ration of num1 i2
        int i2 = 1;
        while (gcd * i2 != num2)
        {
            i2++;
        }
    
        oran = string.Concat(quotient, " ", i1,"/",i2);
        return oran;
    }
    

    Output will be as follow:
    coff num1 / num2

提交回复
热议问题