Search code examples
javaaspect-ratio

Calculation Aspect Ratio returning 0.0


I am trying to make a method to calculate aspect ratio for resizing something.

public float ARC(int oHeight, int oWidth, float nWidth)
{
    float h = (oHeight / oWidth) * (nWidth);
    return h;
}

and to run I am using:

System.out.println(ARC(65, 375, 375));

64 being asigned to oHeight, 375 to oWidth and 375 to nWidth.

But when I test the code, the output is: 0.0? The result is supposed to be 65


Solution

  • (This question was already answered in two comments by Chris Martin but he didn't post an answer)

    The problem is that you're doing integer division, not floating-point division, so while you expect:

    65 / 375 = 0.17...  
    

    You actually get:

    65 / 375 = 0
    

    The is because the decimal part gets cut off. You need to cast the first int (Either first or second, but I find that most readable and least error-prone) to float:

    float h = ( (float) oHeight / oWidth) * (nWidth);