calculate aspect ratio

  • Thread starter Thread starter neverstill
  • Start date Start date
N

neverstill

Hello-

I need to calculate the aspect ratio of an image. This is stumping me...

int w = 190;
int h = 260;

decimal r = w/h; // this is always 0

Now, I have never tried to do this before, I have never even worked with a
decimal before.. so I may be missing some modifier, but I can't find much
online.
the above code should have yielded: 0.73

What am I missing?

Thanks for any help!
Steve
 
Hi Steve,

You need to use the decimal.Divide method. Like this:

int w = 190;
int h = 260;

decimal r = decimal.Divide(w,h);

That's it.

Doug
 
In C#, the result of an operation is typed to the closest match of the
operands (there's a table in the help file somehwere if you want something
more comprehensive).
If you divide two integers, you will get an integer result.
Change the ints to decimal, or you can cast/convert the operands. Either
way.

-Rob Teixeira [MVP]
 
Thanks Doug, this worked great!


Doug said:
Hi Steve,

You need to use the decimal.Divide method. Like this:

int w = 190;
int h = 260;

decimal r = decimal.Divide(w,h);

That's it.

Doug
 
OK, my code sample was overly simple. I actually had
decimal r = (decimal)(w/h);

So that should have worked, no?

Thanks for the response! :)
 
No.

Technically, you need to do this:

decimal r = (decimal)w / (decmial)h;

But you might be able to get away with:

decimal r = (decimal)w / h;

I still prefer the first because your intent is clearer, and someone reading
the code will be able to see what casts are taking place.
 
Matthew W. Jackson said:
Technically, you need to do this:

decimal r = (decimal)w / (decmial)h;

But you might be able to get away with:

decimal r = (decimal)w / h;

No, technically you only need to do the second. The (admittedly
complicated) rules to decide which operator to choose take care of the
rest. I agree that the first is clearer though.
 
Back
Top