Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate a Ratio in C#

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) when supplies with two integers (eg 800 and 600).

string GetRatio(Int A, Int B) {
    // Code I'm looking for
    return Ratio;
}
like image 707
GateKiller Avatar asked Feb 09 '09 11:02

GateKiller


People also ask

How do you take a ratio in C++?

1) ratio_add: This template alias is used to add two ratios and return the result in the simplest form. It returns two-member constants, num, and den denoting numerator and denominator. 2) ratio_subtract: This template alias is used to subtract two ratios and return the result in the simplest form.


2 Answers

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);
}
like image 53
Konrad Rudolph Avatar answered Oct 15 '22 11:10

Konrad Rudolph


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)
like image 31
Tomas Pajonk Avatar answered Oct 15 '22 12:10

Tomas Pajonk