简体   繁体   English

计算宽高比返回0.0

[英]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. 64分配给oHeight,375分配给oWidth,375分配给nWidth。

But when I test the code, the output is: 0.0? 但是当我测试代码时,输​​出为:0.0? The result is supposed to be 65 结果应该是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 : 您需要将第一个intfloat (无论是第一个还是第二个,但我发现可读性最高且最不容易出错):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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