Typecasting int to float before division. Which casts do I really need and which can I remove and why?

Keith Loughnane :

When dividing by ints and I want the result to be a float I can end up with something like this.

float ratio = landscape ? 
              ((float) image.getWidth()) / ((float)image.getHeight()) : 
              ((float)image.getHeight()) / ((float)image.getWidth());

However I think I don't need every cast. When diving sometimes it seems to be auto casted. What are the rules, when does this happen?

Jon Skeet :

You need to cast at least one operand per division. The other operand will be promoted automatically.

I'd personally extract local variables though, at which point it's all implicit (which is why I'd have a comment):

// Use floating point promotion to avoid integer division
float width = image.getWidth();
float height = image.getHeight();
float ratio = landscape ? width / height : height / width;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85645&siteId=1