简体   繁体   中英

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

(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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM