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;
}
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.
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);
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With