C #: how to calculate aspect ratio

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

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

Thanks.

+7
source share
4 answers

You need to find the Greatest Common Divisor and split both x and y on 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 to process something like 16:10 (which can be divided into two, 8: 5 will be returned using the method above), you need to have a table of predefined pairs ((float)x)/y -aspect ratio

+8
source

Since you only need to decide between 16: 9 and 4: 3, here is 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"; } 
+5
source

There are only a few standard ratios: 4:3 , 5:4 , 16:10 , 16:9 . GCD is a good idea, but it will fail, at least in terms of 16:10 and 1366x768 .

A pure GCD algorithm will get 683:384 for 1366x768, because 683 is simple and the resolution is almost 16: 9 (16.0078125).

I believe that for real tasks it is necessary to implement a rather complicated algorithm:

First try out the known proportions (find them on wikipedia ), making some mistakes and only then use the GCD as a backup.

Do not forget about 32:10 ; -)

+3
source

You need to find the GCD (http://en.wikipedia.org/wiki/Greatest_common_divisor) and then:

 return x/GCD + ":" + y/GCD; 
+1
source

All Articles