Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# Help with division

Status
Not open for further replies.

jgd1234567

Programmer
May 2, 2007
68
GB
Hi, i haven't been programming in c# for long and was wondering how i could rewrite the code below to be alot nice:

Code:
int width = 100;
int height = 130;
float ratio = (float)image.Width / (float)image.Height;

if ((float)width / (float)height > ratio)
  width = (int)Math.Round((float)height * (float)ratio);
else
  height = (int)Math.Round((float)width / (float)ratio);

I haven't quite mastered the art of casting. Appreciate your help. Thanks
 
theres not much you can do to make it "nicer?", except remove a few uneccesary casts

Code:
float width = 100;
float height = 130;
float ratio = (float)image.Width / (float)image.Height;

if (width / height > ratio)
  width = Math.Round(height * ratio);
else
  height = Math.Round(width / ratio);

but then I'm assuming you're going to use these for creating a new image, in which case, you would cast them one more time:

Code:
Bitmap newImage = new Bitmap((int)height,(int)width);

But that's still less casting overall. Remember, casting doesnt only make for ugly code, its slow. It should be minimized as much as possible.
 
Hi cheers for your help NeilTrain. I am coming from a php background. I like c# and the compiler can be great but something as simple as division often become abit of a mess.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top