简体   繁体   English

为什么用Java计算错误?

[英]Why is my calculation in Java wrong?

I use this code to calculate something but in nearly every case the result is 0.0. 我使用此代码来计算内容,但几乎在每种情况下,结果均为0.0。 Why? 为什么? There are no warnings or errors in the compiler. 编译器中没有警告或错误。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        int potsum = Integer.valueOf(jTextField1.getText());
        int bla = Integer.valueOf(jTextField2.getText());
        float result = ((Integer.valueOf(bla)/Integer.valueOf(potsum)) * 100);
        jLabel3.setText(Float.toString(result));
    } catch (NumberFormatException e) {
        System.out.println("Error!");
    }
}

This is because this is a integer on integer division. 这是因为这是整数除法中的整数。 Cast both of them to float before the division and you should get correct results. 将它们都抛到除法之前,您应该获得正确的结果。

float result = ((Integer.valueOf(bla)/Integer.valueOf(potsum)) * 100);

is performing integer division, which floors the value (1/2 => 0, 2/3 => 0, 3/3 => 1). 正在执行整数除法,将值底限设置为(1/2 => 0,2/3 => 0,3/3 => 1)。

Consider typecasting or making the numerator/denominator of division a floating point value. 考虑类型转换或使除法的分子/分母为浮点值。

float result = Integer.valueOf(bla) * 100.0f / Integer.valueOf(potsum);

or 要么

float result = (float)Integer.valueOf(bla) / Integer.valueOf(potsum) * 100.0f;

or 要么

float result = Integer.valueOf(bla) / (float)Integer.valueOf(potsum) * 100.0f;

I'll add that I often see people place the division as the last operator in the expression, mostly because that clarifies intent and doesn't require people to understand order of operations + how evaluation is from left to right. 我要补充一点,我经常看到人们将除法运算符放在表达式中的最后一个运算符,主要是因为这澄清了意图,并且不需要人们理解运算的顺序以及从左到右的求值方式。

You need to convert to float, otherwise it looks like integer arithmetic to Java. 您需要将其转换为浮点数,否则对于Java而言它看起来像整数算术。

float result = bla * 100f/ potsum;

Notice the correct calculation for percentages. 注意正确的百分比计算。

float result = ((Float.valueOf(bla)/Float.valueOf(potsum)) * 100);

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

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