Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : How to calculate aspect ratio

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.

like image 701
user1321391 Avatar asked Apr 09 '12 07:04

user1321391


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Why do we write C?

We write C for Carbon Because in some element the symbol of the element is taken form its first words and Co for Cobalt beacause in some elements the symbol of the element is taken from its first second letters, so that the we don't get confuse.


2 Answers

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

like image 161
Pavel Krymets Avatar answered Sep 19 '22 15:09

Pavel Krymets


Since you only need to decide between 16:9 and 4:3, here's a much simpler solution.

public string AspectRatio(int x, int y)
{
    double value = (double)x / y;
    if (value > 1.7)
        return "16:9";
    else
        return "4:3";
}
like image 45
Jack Avatar answered Sep 22 '22 15:09

Jack