C# : How to calculate aspect ratio

user1321391 picture user1321391 · Apr 9, 2012 · Viewed 14.2k times · Source

I am relatively new to programming. I need to calculate the aspect ratio(16:9 or 4:3) from a given dimension say axb. How can I achieve this using C#. Any help would be deeply appreciated.

public string AspectRatio(int x, int y)
{
 //code am looking for
 return ratio
}

Thanks.

Answer

Pavel Krymets picture Pavel Krymets · Apr 9, 2012

You need to find Greatest Common Divisor, and divide both x and y by it.

static int GCD(int a, int b)
{
    int Remainder;

    while( b != 0 )
    {
        Remainder = a % b;
        a = b;
        b = Remainder;
    }

    return a;
}

return string.Format("{0}:{1}",x/GCD(x,y), y/GCD(x,y));

PS

If you want it to handle something like 16:10 (which can be divided by two, 8:5 will be returned using method above) you need to have a table of predefined ((float)x)/y-aspect ratio pairs