如何在Java中将1除以25(1/25)并获得结果.04

问题描述:

如果使用普通BODMAS操作执行,则返回 0 .

It returns 0 if performed with plain BODMAS operation.

我有这样的东西:

int mbUsed=1;

int mbTotal=25;

int percent=(mbUsed/mbTotal)*100;

Java 中的 int 数据类型包含整个值.您应该将值存储在 double float 数据类型中,因为它们可以包含小数点.

The int data type in Java contains whole values. You should instead store your values in the double or float data types, as they can contain decimal points.

在这里您可以看到一个示例:

Here you can see an example:

public static void main(String[] args) {

    int iVal1 = 1;
    int iVal2 = 25;
    int iVal3 = iVal1 / iVal2;

    System.out.println("Integer storage, int variables: " + iVal3);

    double dVal1 = iVal1 / iVal2;

    System.out.println("Double storage, int variables: " + dVal1);

    double dVal2 = (double) iVal1 / (double) iVal2;

    System.out.println("Double storage, double variables: " + dVal2);
}

哪个输出:

Integer storage, int variables: 0
Double storage, int variables: 0.0
Double storage, double variables: 0.04

请注意,您要除法的值还必须至少具有 double 个精度.在我的示例中,我只是简单地将其类型转换为 double (看到它们是整数,就没有区别),但是您也可以将它们存储在 double 数据类型中也一样

Notice how the values you are dividing also have to have at least double precision. In my example I simply type cast them to a double (seeing as they are whole numbers, it will make no difference), but you could also store them in double data types as well.